我想在我的angular 8应用程序上使用crypto-js。
这是我的示例代码:
import {Injectable} from '@angular/core';
import * as CryptoJS from 'crypto-js';
@Injectable()
export class HprotoService {
public enc(msg: string): string {
return CryptoJS.AES.encrypt(msg, '1234').toString();
}
public dec(encMsg: string): string {
return CryptoJS.AES.decrypt(encMsg, '1234').toString(CryptoJS.enc.Utf8);
}
}
和我的组件:
import {Component} from '@angular/core';
import {HprotoService} from './hproto.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
private hproto: HprotoService;
constructor(hproto: HprotoService) {
this.hproto = hproto;
}
public encrypt() {
console.log(this.hproto.enc('Hello dear !!!'));
}
}
我的问题是Crypto-JS在此示例中总是返回不同的哈希值!
U2FsdGVkX19E9JKokPiRUZlrWsykZqAIEVw7ftbBbiA =
U2FsdGVkX1 + 8qW19xOpLCy1Zt5lcyxE3LIKrhs5VmjI =
U2FsdGVkX1 / I2AuJM3jBgHuASmWQvkgmaL0RMsR2LXA =
U2FsdGVkX1 + tR17ftLYsWGoEcRA0 + zmSjkLHJE3zul0 =
我认为该库在我的密码上添加了随机盐。
如何禁用此功能?
答案 0 :(得分:3)
AES
旨在生成对称的随机输出(可以解密)
CryptoJS
AES
在加密过程中使用Math.random()
调用来生成矩阵/盐,并且此随机性包含在加密结果中,这就是解密如何“解密”加密数据的方式。 / p>
您可以 分叉CryptoJS库,并用自己的种子替换Math.random
使用情况 ,也可以 更改{ {1}}在加密期间运行。 。
借助Javascript,您可以将自定义代码分配给Math.random
。
这里是选项#2。它将始终返回相同的输出,它使用函数native function
。这将在回调函数持续时间内暂时更改fakeMathRandom
的结果
fakeMathRandom函数
Math.random
用法
function fakeMathRandom(callBack) {
if(!callBack) throw new Error("Must provide callBack function");
//fake predefined output setup
let seed=0;
const randomOutputs = [0.04,0.08,0.15,0.16,0.23,0.42,0.52,0.65,0.79,0.89];
//save nativeFunction
const Math_random = Math.random;
//change nativeFunction
Math.random = function() {return randomOutputs[seed++ % 10];}
//runs the callback
const callbackOutput = callBack();
//restore nativeFunction
Math.random = Math_random;
return callbackOutput;
}
完整的演示代码:
var encrypted = fakeMathRandom(() => CryptoJS.AES.encrypt(text, key));
function fakeMathRandom(callBack) {
if(!callBack) throw new Error("Must provide callBack function");
let seed=0;
const randomOutputs = [0.04,0.08,0.15,0.16,0.23,0.42,0.52,0.65,0.79,0.89];
const Math_random = Math.random;
Math.random = function() {return randomOutputs[seed++ % 10];}
const callbackOutput = callBack();
Math.random = Math_random;
return callbackOutput;
}
var text = "Text to crypt!!!.";
var key = 'secret';
var encrypted = fakeMathRandom(() => CryptoJS.AES.encrypt(text, key)); //This will always return U2FsdGVkX18KPXCjFHrhR4Q5zBbjCf+I/m/w9jbS3EuvE59kzUxK45FrGHDpqalt
var encrypted2 = fakeMathRandom(() => CryptoJS.AES.encrypt(text, key));
var encrypted3 = fakeMathRandom(() => CryptoJS.AES.encrypt(text, key));
var decrypted = CryptoJS.AES.decrypt(encrypted, key).toString(CryptoJS.enc.Utf8);
document.getElementById('encrypted').innerHTML = encrypted
document.getElementById('encrypted2').innerHTML = encrypted2
document.getElementById('encrypted3').innerHTML = encrypted3
document.getElementById('decrypted').innerHTML = decrypted
我希望能解决您的问题!