1、数据传输:在网络通信或数据存储中,将字符串转换为十六进制格式可以确保数据的可靠传输和存储。十六进制字符串只包含数字和字母,而不涉及控制字符或其他特殊字符,因此避免了特殊字符在传输过程中引起的问题
2、数据校验:十六进制字符串可以用于数据校验和验证。通过对原始字符串进行加密转换,我们可以在接收到数据后重新计算校验和,并与发送方提供的校验和进行比较,以确保数据的完整性和准确性。
3、数据存储:在某些情况下,需要将字符串存储为一种不易读取的形式,例如密码存储或敏感信息的存储。将字符串加密为十六进制字符串可以增加数据的安全性,使其对未经授权的人员更难以理解和使用。
import './utils/proto.js';
import Vue from 'vue';
// function encodeUTF8(s) {
// var i, r = [], c, x;
// for (i = 0; i < s.length; i++)
// if ((c = s.charCodeAt(i)) < 0x80) r.push(c);
// else if (c < 0x800) r.push(0xC0 + (c >> 6 & 0x1F), 0x80 + (c & 0x3F));
// else {
// if ((x = c ^ 0xD800) >> 10 == 0) //对四字节UTF-16转换为Unicode
// c = (x << 10) + (s.charCodeAt(++i) ^ 0xDC00) + 0x10000,
// r.push(0xF0 + (c >> 18 & 0x7), 0x80 + (c >> 12 & 0x3F));
// else r.push(0xE0 + (c >> 12 & 0xF));
// r.push(0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
// };
// return r;
// }
function encodeUTF8(s) {
const code = encodeURIComponent(s)
const bytes = []
for (var i = 0; i < code.length; i++) {
const c = code.charAt(i)
if (c === '%') {
const hex = code.charAt(i + 1) + code.charAt(i + 2)
const hexVal = parseInt(hex, 16)
bytes.push(hexVal)
i += 2
} else bytes.push(c.charCodeAt(0))
}
return bytes
}
Vue.prototype.$sha1 = function(s) {
var data = new Uint8Array(encodeUTF8(s))
var i, j, t;
var l = ((data.length + 8) >>> 6 << 4) + 16, s = new Uint8Array(l << 2);
s.set(new Uint8Array(data.buffer)), s = new Uint32Array(s.buffer);
for (t = new DataView(s.buffer), i = 0; i < l; i++)s[i] = t.getUint32(i << 2);
s[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
s[l - 1] = data.length << 3;
var w = [], f = [
function () { return m[1] & m[2] | ~m[1] & m[3]; },
function () { return m[1] ^ m[2] ^ m[3]; },
function () { return m[1] & m[2] | m[1] & m[3] | m[2] & m[3]; },
function () { return m[1] ^ m[2] ^ m[3]; }
], rol = function (n, c) { return n << c | n >>> (32 - c); },
k = [1518500249, 1859775393, -1894007588, -899497514],
m = [1732584193, -271733879, null, null, -1009589776];
m[2] = ~m[0], m[3] = ~m[1];
for (i = 0; i < s.length; i += 16) {
var o = m.slice(0);
for (j = 0; j < 80; j++)
w[j] = j < 16 ? s[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1),
t = rol(m[0], 5) + f[j / 20 | 0]() + m[4] + w[j] + k[j / 20 | 0] | 0,
m[1] = rol(m[1], 30), m.pop(), m.unshift(t);
for (j = 0; j < 5; j++)m[j] = m[j] + o[j] | 0;
};
t = new DataView(new Uint32Array(m).buffer);
for (var i = 0; i < 5; i++)m[i] = t.getUint32(i << 2);
var hex = Array.prototype.map.call(new Uint8Array(new Uint32Array(m).buffer), function (e) {
return (e < 16 ? "0" : "") + e.toString(16);
}).join("");
return hex;
}
mounted() {
this.sha1 = this.$sha1('abcefg123456')
this.sha2 = this.$sha1('abcefg1234567')
console.log(this.sha1);//ee5a36a1075b985802d52220faa7c444e37dcd8a
console.log(this.sha2);//5a3dbbb59fd2bbb5d6e2aa70783abb999e6b9c92
},