providing values to Crypto-js

巧了我就是萌 提交于 2019-12-13 08:42:42

问题


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.

  1. The encryption key needs to be unique for each user.

  2. Use a full length key: 128, 192 or 256 bits for AES.

  3. It is best to use a full length encryption key of random bytes obtained from a CSPRNG (Cryptographically Secure Random Number Generator).

  4. 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.

  5. 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.

  6. It is best to fully specify all encryptions parameters such as mode and padding for interoperability.

  7. If there is the possibility of entering an incorrect key or an attacker replacing a file add encryption authentication.

  8. Add a version indicator to the encrypted data so changes can be made in the future if necessary.

  9. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!