问题描述
当我清楚地创建了密钥,它在内存中,因此应该可以访问时,为什么会爆炸?
scala> import javax.crypto.{KeyGenerator,SecretKey}
import javax.crypto.{KeyGenerator,SecretKey}
scala> val keyGen = KeyGenerator.getInstance("AES")
val keyGen: javax.crypto.KeyGenerator = javax.crypto.KeyGenerator@3a72e2e8
scala> keyGen.init(128)
scala> val key = keyGen.generateKey
val key: javax.crypto.SecretKey = javax.crypto.spec.SecretKeySpec@fffe83f5
scala> key.destroy
javax.security.auth.DestroyFailedException
at javax.security.auth.Destroyable.destroy(Destroyable.java:53)
... 33 elided
使用 Java 15。
解决方法
返回/生成的 SecretKey虽然实现了 Destroyable
接口,但不会覆盖 destroy()
方法的默认实现Destroyable
接口。
这意味着调用 Destroyable 接口中的默认 destroy() 方法并引发此异常。
public default void destroy() throws DestroyFailedException {
throw new DestroyFailedException();
}
这是在 Destroyable:53 行。
截至目前,似乎没有办法从内存中清除密钥。一种可能的方法是使用反射使键的 byte[] 数组通过覆盖它在内存中被清除。