我正在寻找一种高效的方法来加密和解码一个数字使用相同的密钥。这不是用于加密或加密任何东西,所以它不需要是安全的。
我有一个唯一的数字,我总是想从密码中得到同样的结果。密码不应该太长(超过6个字符)。我确实关心速度,因为我将制造大约1000毫秒的密码。
我将看到的最大数字是100,000,000,考虑字母数字=26个小写字母+26个大写字母,以及6个字符的10个数字,大约是5.680 * 10^9组合,这就足够了。
伪码示例:
let num_to_cypher = 1;
let cypher = cypher_this_number(num_to_cypher); // ==> Ax53iw
let decypher = decypher_this_number(cypher); // ==> 1
let num_to_cypher_ex_2 = 12
let cypher_ex_2 = cypher_this_number(num_to_cypher_ex_2); // ==> 2R5ty6
let decypher_ex_2 = decypher_this_number(cypher_ex_2); // ==> 1编辑1:
我本可以这样做,但在这个例子中我不能定义密码的长度,我不关心加密,所以我可以使用更快的方法。
function encrypt(text){
let cipher = crypto.createCipher('aes128','d6F3Efeq')
let crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}
function decrypt(text){
let decipher = crypto.createDecipher('aes128','d6F3Efeq')
let dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}发布于 2022-09-23 17:45:50
我会使用一个很好的散列函数。这两个算法是相当不错的哈希算法:
编辑注意到.
由于您似乎需要双向编码,所以基地-64可能是您的朋友。
这将编码和解码任何32位有符号整数值(从-2,147,483,648到+2,147,483,647到6个字符)。
const {Buffer} = require('buffer');
const buf = Buffer.alloc(4);
const pad = [ '' , '', '==' , '=' ];
const MIN_INT32 = -2_147_483_648; // 0x80000000
const MAX_INT32 = +2_147_483_647; // 0x7FFFFFFF
function encode(n) {
if ( !Number.isInteger(n) || n < MIN_INT32 || n > MAX_INT32 ) {
throw new RangeError("n must be a valid 32-bit integer such that m is -2,147,483,648 >= m <= +2,147,483,647");
}
buf.writeInt32BE(n) ;
const b64 = buf.toString('base64').slice(0,-2);
return b64;
}
function decode(s) {
const b64 = s + pad[ s.length % 4 ];
buf.fill(b64, 'base64');
const n = buf.readInt32BE();
return n;
}有了这个,简单的问题是:
onst n0 = 123_456_789;
const b64 = encode(n0);
const n1 = decode(b64);
console.log(`original: ${n0}` ) ;
console.log(`encoded: ${b64}` ) ;
console.log(`decoded: ${n1}` ) ;它产生:
original: 123456789
encoded: B1vNFQ
decoded: 123456789https://stackoverflow.com/questions/73829640
复制相似问题