用加密加密。加密失败,解密工作完美

时间:2012-08-24 00:18:31

标签: java android encryption mcrypt

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;
            }
    }

主要

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 ) );
解密返回:“要加密的文字”(正确反映加密的内容,加密后有“”)

我把它缩小到这条线:
encrypted = cipher.doFinal(padString(text).getBytes());

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

正确加密后,“要加密的文字”应变成“cb4b4ca864213684070465b38783a6c8”

1 个答案:

答案 0 :(得分:3)

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

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

最简单的解决方案是在Java中使用填充工具中的buit。您将密码指定为:"AES/CBC/NoPadding"。将此更改为"AES/CBC/PKCS5Padding"以进行加密和解密。不要担心密文的样子,只要检查明文是否与字符串为decyphered cyphertext匹配。

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

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

和另一边相似。不要依赖系统默认值始终相同。

相关问题