问题
I've got CyryptoJs working (as a service), but I don't think I'm observing best practices with it.
import { Injectable } from '@angular/core';
import * as CryptoJS from "crypto-js";
@Injectable()
export class EncryptionService {
constructor() {
}
secretKey: string = "fnord";
encrypt(jsonObj) {
return CryptoJS.AES.encrypt(JSON.stringify(jsonObj), this.secretKey);
}
decrypt(data) {
if (data !==null && data.length > 0) {
var bytes = CryptoJS.AES.decrypt(data.toString(), this.secretKey);
return bytes.toString(CryptoJS.enc.Utf8);
} else {
return "";
}
}
}
secretKey should probably not be exposed like that. What would be a smart way to deliver that value?
回答1:
There are a few security issues.
The encryption key needs to be unique for each user.
Use a full length key: 128, 192 or 256 bits for AES.
It is best to use a full length encryption key of random bytes obtained from a CSPRNG (Cryptographically Secure Random Number Generator).
Using a string for the key, especially a short one is not secure. If you need the user to enter a password use a key derivation function such as PBKDF2 (Password Based Key Derivation Function 2) function to derive a secure encryption key.
There needs to an IV (Initialization Vector) supplied and it needs to be a random byte array from a CSPRNG unique for each encryption. Just prefix the encrypted data with the IV for use during decryption, it does not need to be secret.
It is best to fully specify all encryptions parameters such as mode and padding for interoperability.
If there is the possibility of entering an incorrect key or an attacker replacing a file add encryption authentication.
Add a version indicator to the encrypted data so changes can be made in the future if necessary.
Finally, how are you going to store the encryption key, there is no easy answer to that.
来源:https://stackoverflow.com/questions/44973478/providing-values-to-crypto-js