使用AES / CBC / NOPADDING在Node中加密并使用相同的算法在JAVA中解密会产生一些垃圾,例如eJJ,.d。* 5。

时间:2019-05-28 12:25:01

标签: java android encryption aes

我必须解密一些使用AES / CBC / NOPADDING算法在Node中加密的文本,但是在JAVA中解密时最终会得到一些垃圾值。请帮助...

节点加密代码:

const iv = "0123456789012345";
ALGORITHM : 'aes-256-cbc',
ACCESS_CODE : MD5('Imgine#123$')

function encrypt(text) {
 var cipher      = crypto.createCipheriv(algorithm, key, iv);
 var encrypted   = cipher.update(text, "utf8", "base64");
 encrypted       += cipher.final("base64"); // to hex

 return encrypted;
}

Java解密代码:

private static final Charset UTF8 = Charset.forName("UTF-8");

    public static String decrypt() throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException,
            InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
    {
        String base64Cipher = "t7rCN8nBGlruCiSvpQ9DPg==";
        byte [] iv = "0123456789012345".getBytes(UTF8);
        byte [] secretBytes = "Imgine#123$".getBytes(UTF8);

        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(secretBytes);

        SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
        cipher.init(Cipher.DECRYPT_MODE, skey, new IvParameterSpec(iv));

        return new String(cipher.doFinal(Base64.getDecoder().decode(base64Cipher))) ;
   }

结果:e�J�,�d�|*�5Ҝ��

1 个答案:

答案 0 :(得分:-1)

最终,我找到了根本原因,罪魁祸首是将密钥转换为MD5并没有按要求进行转换,MessageDigest将密钥转换为128位,必须为256位,我正在使用以下方法转换所需的密钥对我有用,谢谢您的宝贵宝贵意见。

public static String getMd5(String input)
{
    try {

        // Static getInstance method is called with hashing MD5
        MessageDigest md = MessageDigest.getInstance("MD5");

        // digest() method is called to calculate message digest
        //  of an input digest() return array of byte
        byte[] messageDigest = md.digest(input.getBytes());

        // Convert byte array into signum representation
        BigInteger no = new BigInteger(1, messageDigest);

        // Convert message digest into hex value
        String hashtext = no.toString(16);
        while (hashtext.length() < 32) {
            hashtext = "0" + hashtext;
        }
        return hashtext;
    }

    // For specifying wrong message digest algorithms
    catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}