-->

加密和解密犯规给使用AES / ECB / NoPadding相同的纯文本(Encrypt and

2019-08-17 06:35发布

String plain1= "Test";
byte[] cipher = SplashSecure.getInstance().encrypt2(plain1);
String plain2 = SplashSecure.getInstance().decrypt2(cipher);

平原=测试

解密后plainText2应等于plaintext 。但它不是。

加密/解密方法。

 public void initKey(String key) {
    String paddedKey = Utils.padString(key);
    mKeyspec = new SecretKeySpec(Utils.getBytes(paddedKey), "AES/ECB/NoPadding");
                   // Utils.getBytes returns "paddedKey.getBytes("CP1252")"
 }

public byte[] encrypt2(String data) {
    try {
        Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, mKeyspec);
        String paddedData = Utils.padString(data);
        return cipher.doFinal(Utils.getBytes(paddedData));

    } catch(InvalidKeyException e) {
        e.printStackTrace();
    // Series of catch blocks
    }
    return null;
}

public String decrypt2(byte[] cypherText) {
    try {
        Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, mKeyspec);
        byte[] plainTextBytes = cipher.doFinal(cypherText);
        return Utils.getString(plainTextBytes);
        // Utils.getString returns "new String(bytes, "CP1252");"
    } catch(InvalidKeyException e) {
        // Series of catch blocks.
    } 
    return null;
}

编辑:

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

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

    return source;
}

编辑:

我试着去得到加密,解密跨Windows工作(其它客户端,加密和服务器)和Android。 Windows客户端是一个VC的应用程序,使用的Rijndael类( http://svn.openfoundry.org/pcman/2007.06.03/Lite/Rijndael.h )和Android使用http://www.cs.ucdavis.edu/ 〜rogaway / OCB / OCB-java的/ Rijndael.java Windows客户端已加密的数据并将其存储在服务器上。 我需要建立Android的客户端取出加密的数据,解密并显示给用户。

我敢肯定,IM使用正确的密钥来解密。

Answer 1:

AES具有128位(即16个字节)的块大小。 它只能在这个大小的块处理数据,因此,即使你告诉它使用NoPadding它无法遵守。

这发生在这里最有可能的是,你正在使用的AES实现内部填充你的四个字节输入最多16个字节,并将结果进行加密。 当你解密,你会得到相同的16个字节退了出来,即“T”,“E”,“S”,“T”和12个字节的垃圾。

您所看到的输出支持这一点:“测试”,其次是24 ? 符号。 我不知道为什么它的印花两大? 每个垃圾字节的符号,但我猜它是与Unicode中解释垃圾字节。 你可以看到什么是打印出解密Blob的原始字节值回事。

简短的回答是,“NoPadding”无厘头分组密码算法(或者说,如果你要使用NoPadding,那么你必须垫和unpad事情自己)。



文章来源: Encrypt and decrypt doesnt give the same plain text using AES/ECB/NoPadding