Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: java.security.InvalidAlgorithmParameterException: Cannot reuse iv for GCM encryption #994

Closed
kute opened this issue Dec 29, 2023 · 0 comments
Assignees
Labels
bug Something isn't working

Comments

@kute
Copy link

kute commented Dec 29, 2023

What happened?

mysqlreader中的password使用 ${enc:时,发现 com.wgzhao.addax.common.util.EncryptUtil类的 encrypt方法,无法多次加密,如下:

@Test
	public void test() {
		EncryptUtil.encrypt("root");
		EncryptUtil.encrypt("root");
	}

报错

Caused by: java.security.InvalidAlgorithmParameterException: Cannot reuse iv for GCM encryption
	at com.sun.crypto.provider.CipherCore.init(CipherCore.java:582)
	at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:346)
	at javax.crypto.Cipher.init(Cipher.java:1397)
	at javax.crypto.Cipher.init(Cipher.java:1330)
	at com.wgzhao.addax.common.util.EncryptUtil.encrypt(EncryptUtil.java:79)

源码

static {
        try {
            final int iterationCount = 40000;
            final int keyLength = 128;
            ivSpec = new IvParameterSpec(iv);
            pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
            PBEKeySpec keySpec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), iterationCount, keyLength);
            SecretKey keyTmp = keyFactory.generateSecret(keySpec);
            secSpec = new SecretKeySpec(keyTmp.getEncoded(), "AES");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String encrypt(String password)
    {
        try {
            pbeCipher.init(Cipher.ENCRYPT_MODE, secSpec, ivSpec);
            byte[] cryptoText = pbeCipher.doFinal(password.getBytes(StandardCharsets.UTF_8));
            return base64Encode(cryptoText);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

这里的 iv每次加密都不能使用同一个,不能 static!!

Version

4.1.3 (Default)

OS Type

No response

Java JDK Version

Oracle JDK 1.8.0

Relevant log output

No response

@kute kute added the bug Something isn't working label Dec 29, 2023
@wgzhao wgzhao closed this as completed in a852982 Jan 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants