在测试中调用spring-security-crypto的加密器时出现IllegalArgumentException

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (17)

我正在尝试为下面的代码编写一个JUnit测试用例。我正在使用spring-security-crypto库的加密器。当我尝试运行代码时,我能够成功加密字符串,但是当我运行测试用例时,我收到错误。

public String standardEncryption(String value) {
        if (!isNullOrEmpty(value)) {
            return Encryptors.text(password, salt).encrypt(value);
        }
        return value;
    }

Junit测试用例

@Test
    public void can_standardEncryption() {
        String value = someNumericString(10);

        String result = encryption.standardEncryption(value);

        assertThat(result).isNotNull();
        assertThat(result.equals(value)).isFalse();
        assertThat(textEncryptor.decrypt(result)).isEqualTo(value);
        assertThat(result.equals(textEncryptor.encrypt(value))).isFalse();
    }

错误

java.lang.IllegalArgumentException: Unable to initialize due to invalid secret key

    at org.springframework.security.crypto.encrypt.CipherUtils.initCipher(CipherUtils.java:120)
    at org.springframework.security.crypto.encrypt.AesBytesEncryptor.encrypt(AesBytesEncryptor.java:115)
    at org.springframework.security.crypto.encrypt.HexEncodingTextEncryptor.encrypt(HexEncodingTextEncryptor.java:36)
    at something(something.java:25)
    at something(something.java:44)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
Caused by: java.security.InvalidKeyException: Illegal key size
    at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1039)
    at javax.crypto.Cipher.implInit(Cipher.java:805)
    at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
    at javax.crypto.Cipher.init(Cipher.java:1396)
    at javax.crypto.Cipher.init(Cipher.java:1327)
    at org.springframework.security.crypto.encrypt.CipherUtils.initCipher
提问于
用户回答回答于

听起来您可能需要启用更大的密钥大小。

默认情况下,Spring Security会根据您提供的密码创建256位AES密钥。但是,Java 8默认情况下不允许使用此大小的密钥。

如果您早于Java 8u151,那么您需要下载一个jar并将其添加到您的安装中,替换$JAVA_HOME/jre/lib/security您下载的内容。

如果您使用的是Java 8u151或更高版本,则默认情况下会发送此策略jar,但需要通过取消注释以下行来启用$JAVA_HOME/jre/lib/security/java.security

crypto.policy=unlimited

或者,我相信OpenJDK默认启用此功能,因此您也可以切换出JVM。

资料来源:https//github.com/open-eid/cdoc4j/wiki/Enabling-Unlimited-Strength-Jurisdiction-Policy

扫码关注云+社区

领取腾讯云代金券