![](/img/trans.png)
[英]java.security.NoSuchAlgorithmException: PKCS11 KeyStore not available, Trying to Enable FIPS mode using SUNPKCS11 in java 11
[英]set and get DES key in java.security.KeyStore PKCS11
我正在嘗試使用從KeyStore加載的des密鑰進行加密,我得到:
Exception in thread "main" java.security.InvalidKeyException: No installed provider supports this key: sun.security.pkcs11.P11Key$P11SecretKey
at javax.crypto.Cipher.chooseProvider(Cipher.java:878)
at javax.crypto.Cipher.init(Cipher.java:1213)
at javax.crypto.Cipher.init(Cipher.java:1153)
這是我的代碼:
public static void main(String[] args) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IOException, CertificateException {
Provider provider = new sun.security.pkcs11.SunPKCS11(DesSaveLoad.class.getClassLoader().getResourceAsStream("pkcs11.cfg"));
Security.removeProvider(provider.getName());
Security.insertProviderAt(provider, 1);
KeyStore keyStore = KeyStore.getInstance("PKCS11", provider);
keyStore.load(null, null);
SecretKey desKey = desGenerateKey();
keyStore.setKeyEntry("t1", desKey, null, null);
SecretKey t1 = (SecretKey) keyStore.getKey("t1", null);
byte[] messageBytes = "message".getBytes();
desEncrypt(messageBytes, 0, messageBytes.length, desKey);
desEncrypt(messageBytes, 0, messageBytes.length, t1); //Exception is thrown here
}
public static SecretKey desGenerateKey() throws NoSuchAlgorithmException {
KeyGenerator keygenerator = null;
keygenerator = KeyGenerator.getInstance("DES");
return keygenerator.generateKey();
}
public static byte[] desEncrypt(byte[] plainText, int offset, int size, SecretKey key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher;
if (size % 8 != 0) {
cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
} else {
cipher = Cipher.getInstance("DES/ECB/NoPadding");
}
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(plainText, offset, size);
}
如您所見,使用生成的des密鑰進行加密時不會引發異常。
如果使用HSM執行加密,則加密過程在HSM中而不是在軟件中執行。 Cipher
本身不實現加密過程。 PKCS#11提供者的基礎CipherSpi
用於Cipher
是根據對init()
調用期間給出的密鑰,使用延遲的提供者選擇來選擇的 。 因此,盡管desEncrypt()
函數似乎執行相同的操作,但實際上,該功能取決於提供程序,並且取決於您的情況,取決於PKCS#11包裝程序,庫以及HSM。
現在PKCS#11是接口規范; 並非PKCS#11中的所有機制都將在每個令牌中實現。 某些加密算法可能太模糊或太不安全。 后者可能是DES ECB的情況,因為該算法非常不安全。 這並不意味着不能普遍使用DES密鑰-它們仍然可以在例如MAC計算中發揮作用。 因此,如果支持DES ECB(在當前設置中),請檢查HSM的文檔。
通過將-Djava.security.debug=sunpkcs11
添加到對Java解釋器( java
或javaw
)的調用中,可以獲取有關PKCS#11方法調用的更多信息。 如果DES不起作用,請嘗試更安全,更通用的"AES/CBC/PKCS5Padding"
或三重DES機制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.