AES加密在不同的机器上返回不同的值

时间:2014-06-03 17:14:11

标签: java encryption cryptography aes

我的AES加密程序在不同的计算机上返回不同的加密值。任何人都可以请求帮助找出需要做什么,以确保在程序运行的任何机器上返回相同的加密值..

private static SecretKeySpec secret;
private static String seed;
private static String text;
private static String salt = "Salt123";
private static int pswdIterations = 65536;
private static int keySize = 256;

/**
 * 
 * @param mySeed
 */
public static void setSeed(String mySeed) {

    try {
        byte[] saltBytes = salt.getBytes("UTF-8");
        PBEKeySpec spec = new PBEKeySpec(mySeed.toCharArray(), saltBytes,
                pswdIterations, keySize);
        SecretKeyFactory factory = SecretKeyFactory
                .getInstance("PBKDF2WithHmacSHA1");
        SecretKey secretKey = factory.generateSecret(spec);
        secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }

}

public static String getEncryptedStringFor(String text) {
    try {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        byte[] encryptedData = cipher.doFinal(text.getBytes("UTF-8"));
        return new String(Base64.encodeBase64(encryptedData));

    } catch (Exception e) {
        System.out.println("Error while encrypting: " + e.toString());
    }
    return null;
}

public static String getDecryptedStringFor(String text) {
    try {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, secret);
        return (new String(cipher.doFinal(Base64
                .decodeBase64(text.getBytes("UTF-8")))));
    } catch (Exception e) {
        System.out.println("Error while decrypting: " + e.toString());
    }
    return null;
}

一些样本值

  • 种子:seed123
  • text:#text!
  • 加密值:RoVE3KsjzN0nNxCNsNpRPg ==

  • 种子:种子!!

  • text:#text123!
  • 加密值:X6pfUKCVXXrAEyqKko / kFQ ==

1 个答案:

答案 0 :(得分:1)

我在代码中唯一能看到的是以下行:

return (new String(cipher.doFinal(Base64.decodeBase64(text.getBytes("UTF-8")))));

现在看起来这样实际上是在用UTF-8解码后返回一个String。但它并没有:它使用平台默认值:

return (new String(
    cipher.doFinal(
        Base64.decodeBase64(
            text.getBytes("UTF-8")
        )
    )
));

当然,第一个(无论如何都是多余的,所以试试这个:

byte[] ciphertext = Base64.decodeBase64(text.getBytes("UTF-8"));
byte[] plaintext = cipher.doFinal(ciphertext);
return new String(plaintext, "UTF-8");

请注意,您现在也可以使用import static java.nio.charsets.StandardCharsets.UTF_8,这样您也可以取消例外。我希望他们能为StandardCiphers做同样的事情.AES_CBC_PKCS7PADDING:)