I am writing an application for digital signature using PKCS#11. The Certum token works on JRE 1.8.0_333 (32-bit) and JRE 1.8.0_441 (32-bit). The CenCertum token works on JRE 1.8.0_333 (32-bit), but on JRE 1.8.0_441 (32-bit), it returns an error:
java.security.InvalidKeyException: No installed provider supports this key: sun.security.pkcs11.P11Key$P11PrivateKey
at java.security.Signature$Delegate.chooseProvider(Unknown Source)
at java.security.Signature$Delegate.engineInitSign(Unknown Source)
at java.security.Signature.initSign(Unknown Source)
at com.example.pkcs11test.PKCS11Test.main(PKCS11Test.java:45)
Line:
signature.initSign(privateKey);
What should be added to the code for initialization or what should be checked to find the cause of the problem?
Code:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.X509Certificate;
import java.util.Base64;
public class PKCS11Test {
public static void main(String[] args) {
try {
// 1. Ścieżka do pliku konfiguracyjnego PKCS#11
String configPath = "/pkcs11.cfg";
String configPath32 = "/pkcs1132.cfg";
String configPathCertum = "/pkcs11_Certum.cfg";
String configPathCertum32 = "/pkcs11_Certum32.cfg";
String PIN = "771216";
// 2. Inicjalizacja dostawcy PKCS#11
Provider provider = loaddllJ8(configPath32);
//loaddllJ21
Security.addProvider(provider);
// 3. Ładowanie keystore z tokena PKCS#11
KeyStore keyStore = KeyStore.getInstance("PKCS11", provider);
keyStore.load(null, PIN.toCharArray()); // PIN do tokena
// 4. Wybór klucza i certyfikatu
String alias = keyStore.aliases().nextElement();
PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, null);
X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
System.out.println("Załadowano klucz i certyfikat:");
System.out.println("Alias: " + alias);
System.out.println("Certyfikat: " + cert);
// 5. Wiadomość do podpisania
String message = "To jest wiadomość testowa.";
byte[] messageBytes = message.getBytes();
// 6. Podpisywanie wiadomości
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(messageBytes);
byte[] signedMessage = signature.sign();
System.out.println("\nPodpis cyfrowy (Base64):");
System.out.println(Base64.getEncoder().encodeToString(signedMessage));
} catch (Exception e) {
e.printStackTrace();
}
}
private static Provider loaddllJ8(String configPath) throws FileNotFoundException, IOException {
InputStream is = PKCS11Test.class.getResourceAsStream(configPath);
Provider p = new sun.security.pkcs11.SunPKCS11(is);
is.close();
return p;
}
}
pkcs1132.cfg:
name = MyPKCS11Device
library = "C:/Program Files (x86)/Encard/enigmap11.dll"
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745304404a4621623.html
评论列表(0条)