有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java加密与加密。加密失败,解密工作正常

MCrypt:

    import java.security.NoSuchAlgorithmException;

    import javax.crypto.Cipher;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;

    public class MCrypt {

            private String iv = "fedcba9876543210";
            private IvParameterSpec ivspec;
            private SecretKeySpec keyspec;
            private Cipher cipher;

            private String SecretKey = "0123456789abcdef";

            public MCrypt()
            {
                    ivspec = new IvParameterSpec(iv.getBytes());

                    keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");

                    try {
                            cipher = Cipher.getInstance("AES/CBC/NoPadding");
                    } catch (NoSuchAlgorithmException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    } catch (NoSuchPaddingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    }
            }

            public byte[] encrypt(String text) throws Exception
            {
                    if(text == null || text.length() == 0)
                            throw new Exception("Empty string");

                    byte[] encrypted = null;

                    try {
                            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);

                            encrypted = cipher.doFinal(padString(text).getBytes());
                    } catch (Exception e)
                    {                       
                            throw new Exception("[encrypt] " + e.getMessage());
                    }

                    return encrypted;
            }

            public byte[] decrypt(String code) throws Exception
            {
                    if(code == null || code.length() == 0)
                            throw new Exception("Empty string");

                    byte[] decrypted = null;

                    try {
                            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

                            decrypted = cipher.doFinal(hexToBytes(code));
                    } catch (Exception e)
                    {
                            throw new Exception("[decrypt] " + e.getMessage());
                    }
                    return decrypted;
            }



            public static String bytesToHex(byte[] data)
            {
                    if (data==null)
                    {
                            return null;
                    }

                    int len = data.length;
                    String str = "";
                    for (int i=0; i<len; i++) {
                            if ((data[i]&0xFF)<16)
                                    str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
                            else
                                    str = str + java.lang.Integer.toHexString(data[i]&0xFF);
                    }
                    return str;
            }


            public static byte[] hexToBytes(String str) {
                    if (str==null) {
                            return null;
                    } else if (str.length() < 2) {
                            return null;
                    } else {
                            int len = str.length() / 2;
                            byte[] buffer = new byte[len];
                            for (int i=0; i<len; i++) {
                                    buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
                            }
                            return buffer;
                    }
            }



            private static String padString(String source)
            {
              char paddingChar = ' ';
              int size = 16;
              int x = source.length() % size;
              int padLength = size - x;

              for (int i = 0; i < padLength; i++)
              {
                      source += paddingChar;
              }

              return source;
            }
    }

Main:

mcrypt = new MCrypt();
/* Encrypt */
String encrypted = MCrypt.bytesToHex( mcrypt.encrypt("Text to Encrypt") );
//Returns 9975e28df055c336a9b7090b03f88689
/* Decrypt */
String decrypted = new String( mcrypt.decrypt( encrypted ) );
//Returns "Text to Encrypt "

问题是:

String encrypted = MCrypt.bytesToHex( mcrypt.encrypt("Text to Encrypt") );
加密返回:9975e28df055c336a9b7090b03f88689(不正确)
String decrypted = new String( mcrypt.decrypt( encrypted ) );
Decrypt返回:要加密的文本(这正确地反映了加密的结果,加密后有一个“”

我把范围缩小到这一行:
encrypted = cipher.doFinal(padString(text).getBytes());

我尝试更改padString函数,以便char paddingChar = 0;而不是char paddingChar = ' ';没有运气

正确加密后,“要加密的文本”应变为“cb4b4ca864213684070465b38783a6c8”


共 (1) 个答案

  1. # 1 楼答案

    AES是块密码。它将一个256位块(=16字节)加密为另一个256位块。您的明文“要加密的文本”是15个字符,或248位。AES无法按原样对其进行加密,但必须添加一些填充以使其成为完整的块

    如果显式添加填充字符,则必须显式删除它。每个不同的填充字符都会对解密产生很大影响。平均而言,更改输入明文块中的一位将更改输出密码块中50%的位

    最简单的解决方案是使用Java中的内置填充功能。将密码指定为:"AES/CBC/NoPadding"。对于加密和解密,将其更改为"AES/CBC/PKCS5Padding"。不要担心密码文本是什么样子,只需逐个字符检查明文是否与解密的密码文本匹配

    一个常见的错误是使用getBytes()将文本字符串转换为字节数组。不要这样做,因为这很容易出错。您应该精确地指定在字符和字节之间使用的映射。使用类似于:

    byte[] plainBytes = plaintextString.getBytes("UTF-8");
    

    另一边也差不多。不要依赖系统默认值始终不变