Javascript相当于Java AES + SecretKeySpec解密

时间:2016-07-06 06:12:24

标签: java node.js aes

下面是我试图转移到NodeJS的java代码。

public static String decryptDataWithKey(String keyString, String base64String) throws Exception {

        //Algorithm
        String AES_ALGORITHM = "AES"; 

        //Key from keystring
        MessageDigest digester = MessageDigest.getInstance("MD5");
        digester.update(keyString.getBytes());
        byte[] password = digester.digest();
        Key key =  new SecretKeySpec(password, AES_ALGORITHM); // what is the equivalent of this line in javascript ?

        //Create decipher
        Cipher c = Cipher.getInstance(AES_ALGORITHM);
        c.init(Cipher.DECRYPT_MODE, key);

        //Get bytes of enc data
        byte[] decodedValue = new BASE64Decoder().decodeBuffer(base64String);

        // Do decrypt
        byte[] decValue = c.doFinal(decodedValue);
        String decryptedValue = new String(decValue);
        return decryptedValue;
    }

我最后写了下面的方法,但得到了异常 - Bad Decrypt

function decryptDataWithKey(keyString, base64String){

        //Algorithm
        let algorithm = 'aes-128-ecb';

        //Key from keystring
        let key = crypto.createHash('md5').update(keyString).digest();

        //Create decipher
        let decipher = crypto.createDecipher(algorithm,key);

        //Get bytes of enc data
        let cipher = new Buffer(base64String, 'base64');

        // Do decrypt
        let decrypted = decipher.update(cipher, 'base64', 'utf-8');
        decrypted += decipher.final('utf-8'); // throwing exception : digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
        return decrypted;
    }

请指导我在这里缺少的东西。我试图避免我的nodejs项目中的jar依赖。我相信这应该可以使用加密来实现。 或者我应该去加密?

0 个答案:

没有答案