繁体   English   中英

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

[英]Encrypted in Node using AES/CBC/NOPADDING and decrypted in JAVA using same algorithm gives some junk like e�J�,�d�|*�5Ҝ��

我必须解密一些使用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Ҝ

最终,我找到了根本原因,罪魁祸首是将密钥转换为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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM