我正在基于angular6开发一个简单的加密消息聊天。到目前为止,使用CryptoJS进行加密一直有效。但是,在移动设备(任何类型)上,性能都非常差。我读了here! WebCrypto在性能和browser support方面要好得多!似乎也很好。
所以我开始从CryptoJS移植到WebCrypto。我可以使用它,但是我以前无法解密CryptoJS加密的消息。
CryptoJS的相关功能是
encrypt = (body: string, key: string): string => {
return CryptoJS.AES.encrypt(body, key).toString();
}
decrypt = (body: string, key: string): string => {
let decrypted = CryptoJS.AES.decrypt(body, key);
return decrypted.toString(CryptoJS.enc.Utf8);
}
createConversationKey = (publicKey: string, privateKey: string, salt: string): string => {
return CryptoJS.PBKDF2(bigInt(publicKey).modPow(privateKey, p).toString(), salt, {
keySize: 512 / 32,
iterations: 1000
}).toString();
我移植到的
encrypt = (body: string) => {
let iv = this.getIV();
return window.crypto.subtle.encrypt(
{
name: this.AES_MODE,
counter: iv,
length: 16
},
this.key,
this.utf2buf(body)
)
.then(v => this.buf2utf(v))
}
decrypt = (body: string, salt) => {
let ciphertext = this.utf2buf(body);
salt = this.utf2buf(salt);
let iv = atob(body).substring(16)
var doDeriveKey = this.PBKDF2(this.key, salt)
return doDeriveKey.then(derivedKey =>{
console.log(derivedKey.toString())
return crypto.subtle.decrypt({ name: this.AES_MODE, counter: iv, length: 64 }, derivedKey, ciphertext)
}
)
.then(v => this.buf2utf(v))
}
createConversationKey = (publicKey: string, privateKey: string, salt: string) => {
return this.PBKDF2(bigInt(publicKey).modPow(privateKey, p).toString(), this.utf2buf(salt));
}
我尝试了iv
和length
的几个选项,因此,总是会返回错误的数据。
是否可以使用WebCrypto解密CryptoJS消息? 据我了解,他们都可以使用AES。
有人可以使用示例代码吗?
谢谢