有 Java 编程相关的问题?

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

java AES加密不同的行为

我有以下代码,非常简单,但是,在Spring工具套件和命令提示符中运行时,代码会产生不同的结果。JDK版本在两种环境中都是相同的。我也尝试了Java8和Java11,但症状相同。还有什么我应该看的吗?这对我来说有点奇怪。非常感谢您对我们的任何帮助

public class CryptoUtil
{
    public final static Charset ENCODING = StandardCharsets.UTF_8;
    public final static String ALGO_AND_PARAMS = "AES/CBC/PKCS5PADDING";
    public final static String ENCR_ALGO = "AES";
    public final static String HASH_ALGO = "PBKDF2WithHmacSHA256";
    public final static int KEYGEN_ITERATIONS = 65536  ;
    public final static int KEYGEN_KEY_SIZE = 256;
    public final static String KEYGEN_SALT = "w4sh3Vzp2ZX6GmPC";
    public final static String KEYGEN_IV = "2QZv3t6OOCLIf6vG";
    
    public static String decrypt(String cyphertext, String password)
        throws Exception
    {

        String plaintext;

        try {

            IvParameterSpec ivspec = new IvParameterSpec(KEYGEN_IV.getBytes(ENCODING));

            SecretKeyFactory factory = SecretKeyFactory.getInstance(HASH_ALGO);
            KeySpec spec = new PBEKeySpec(password.toCharArray(), KEYGEN_SALT.getBytes(ENCODING), KEYGEN_ITERATIONS, KEYGEN_KEY_SIZE);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), ENCR_ALGO);

            Cipher cipher = Cipher.getInstance(ALGO_AND_PARAMS);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
            plaintext = new String(cipher.doFinal(Base64.getDecoder().decode(cyphertext)));

        } catch (Exception e) {
            throw new Exception("Error while decrypting " + cyphertext, e);
        }

        return plaintext;
    }

    public static String encrypt(String plaintext, String password)
            throws Exception
    {
        String cyphertext;

        try {

            IvParameterSpec ivspec = new IvParameterSpec(KEYGEN_IV.getBytes(ENCODING));

            SecretKeyFactory factory = SecretKeyFactory.getInstance(HASH_ALGO);
            KeySpec spec = new PBEKeySpec(password.toCharArray(), KEYGEN_SALT.getBytes(ENCODING), KEYGEN_ITERATIONS, KEYGEN_KEY_SIZE);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), ENCR_ALGO);

            Cipher cipher = Cipher.getInstance(ALGO_AND_PARAMS);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
            cyphertext = new String(Base64.getEncoder().encode(cipher.doFinal(plaintext.getBytes(ENCODING))));

        } catch (Exception e) {
            throw new Exception("Error while encrypting " + plaintext, e);
        }

        return cyphertext;
    }
}

共 (0) 个答案