mah*_*454 4 javascript cryptojs angular
我想在我的 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);
}
}
Run Code Online (Sandbox Code Playgroud)
和我的组件:
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 !!!'));
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是 Crypto-JS 在这个例子中总是返回不同的哈希值!
U2FsdGVkX19E9JKokPiRUZlrWsykZqAIEVw7ftbBbiA =
U2FsdGVkX1 + 8qW19xOpLCy1Zt5lcyxE3LIKrhs5VmjI =
U2FsdGVkX1 / I2AuJM3jBgHuASmWQvkgmaL0RMsR2LXA =
U2FsdGVkX1 + tR17ftLYsWGoEcRA0 + zmSjkLHJE3zul0 =
我认为这个库在我的密码中添加了随机盐。
如何禁用此功能?
AES 旨在生成对称的随机输出(可以解密)
CryptoJS AESMath.random()在加密期间使用调用来生成矩阵/盐,并且这种随机性包含在加密结果中,这就是解密可以“解密”加密数据的方式。
您可以分叉 CryptoJS 库并用Math.random您自己的种子替换使用,或者您可以在加密期间更改Math.random运行时的结果。
感谢 Javascript,您可以将自定义代码分配给native function.
这是选项#2。它将始终返回相同的输出,它使用函数fakeMathRandom。这将Math.random在回调函数的持续时间内暂时改变结果
fakeMathRandom 函数
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;
}
Run Code Online (Sandbox Code Playgroud)
用法
var encrypted = fakeMathRandom(() => CryptoJS.AES.encrypt(text, key));
Run Code Online (Sandbox Code Playgroud)
完整的演示代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
var encrypted = fakeMathRandom(() => CryptoJS.AES.encrypt(text, key));
Run Code Online (Sandbox Code Playgroud)
我希望能解决你的问题!
| 归档时间: |
|
| 查看次数: |
996 次 |
| 最近记录: |