I am using SoftHSM and am able to generate and store keys in a token. In order to use SunPKCS Interfaces many methods require the session handle and i am at a loss on how to retrieve them.
Currently i am using SoftHSM and PKCS11 as follows. THe code within the comments are what i tried to work with the SUNPKCS11 interface signatures.
Any example code on how to wrap and unwrap keys will also be much appreciated. I am attempting to backup keys using PKCS11 from one token to another and if my understanding is right, the approach must be via wrapping....
Sitaraman
public static void main(String[] args) {
// TODO code application logic hereString configName = "softhsm.cfg";
try {
// Set up the Sun PKCS 11 provider
String configName = "/etc/softhsm.cfg";
Provider p = new SunPKCS11(configName);
String configName1 = "/etc/softhsm1.cfg";
Provider p1 = new SunPKCS11(configName1);
if (-1 == Security.addProvider(p)) {
throw new RuntimeException("could not add security provider");
}
PKCS11 p11 = PKCS11.getInstance("/usr/local/lib/softhsm/libsofthsm.so", "C_GetFunctionList", null, false);
/* p11.C_GetSessionInfo(0);
CK_INFO cki = p11.C_GetInfo();
long[] slots = p11.C_GetSlotList(true);
String label = new String(p11.C_GetTokenInfo(slots[0]).label);
Object obj = new Object();
long sessionhandle = p11.C_OpenSession(slots[0], 1, null, null);
CK_MECHANISM ckm = new CK_MECHANISM();
ckm.mechanism = PKCS11Constants.CKM_RSA_PKCS;
CK_ATTRIBUTE[] cka = new CK_ATTRIBUTE[1];
CK_ATTRIBUTE[] cka1 = new CK_ATTRIBUTE[1];
long[] keypair =p11.C_GenerateKeyPair(slots[1], ckm, cka, cka1);
*/
//System.out.println("No. of slots" + slots.length + "label" + label);
// Load the key store
char[] pin = "vit12345".toCharArray();
char[] pin1 = "User12345".toCharArray();
KeyStore ks = KeyStore.getInstance("PKCS11", p);
KeyStore ks1 = KeyStore.getInstance("PKCS11", p1);
ks.load(null, pin);
ks1.load(null, pin1);
Entry e;
KeyStore.PrivateKeyEntry e1;
// Generate the key
SecureRandom sr = new SecureRandom();
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", p);
keyGen.initialize(1024, sr);
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey pk = keyPair.getPrivate();
// Java API requires a certificate chain
X509Certificate[] chain = generateV3Certificate(keyPair);
ks.setKeyEntry("ALIAS-GOES-HERE", pk, "1234".toCharArray(), chain);
//ks1.setKeyEntry("ALIAS-GOES-HERE1", pk, "1234".toCharArray(), chain);
ks.store(null);
//ks1.store(null);
Key k = ks.getKey("ALIAS-GOES-HERE", "1234".toCharArray());
System.out.println("key string is " + k.toString());
PrivateKey pk1 = (PrivateKey) k;
System.out.println("OK");
} catch (Exception ex) {
ex.printStackTrace();
}
}
You can use approach from SunPKCS11 wrapper like you do in commented block in your sample code.
You can obtain a session handle by the following sample code:
CK_C_INITIALIZE_ARGS initArgs = new CK_C_INITIALIZE_ARGS();
PKCS11 p11 = PKCS11.getInstance("D:\\cryptoki.dll", "C_GetFunctionList", initArgs, false);
long hSession = p11.C_OpenSession(0, CKF_SERIAL_SESSION| CKF_RW_SESSION, null, null);
char [] pin = {'1', '2', '3', '4', '5', '6', '7', '8'};
p11.C_Login(hSession, CKU_USER, pin);
// do work
p11.C_Logout(hSession);
p11.C_CloseSession(hSession);
For example to generate AES key and obtain a handle to generated key use the following (as an example):
CK_ATTRIBUTE[] aesKeyObject = new CK_ATTRIBUTE[13];
try
{
aesKeyObject[0] = new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY);
aesKeyObject[1] = new CK_ATTRIBUTE(CKA_KEY_TYPE, CKK_AES);
aesKeyObject[2] = new CK_ATTRIBUTE(CKA_VALUE_LEN, 32);
aesKeyObject[3] = new CK_ATTRIBUTE(CKA_TOKEN, true);
aesKeyObject[4] = new CK_ATTRIBUTE(CKA_LABEL, label);
aesKeyObject[5] = new CK_ATTRIBUTE(CKA_PRIVATE, true);
aesKeyObject[6] = new CK_ATTRIBUTE(CKA_EXTRACTABLE, false);
aesKeyObject[7] = new CK_ATTRIBUTE(CKA_WRAP, true);
aesKeyObject[8] = new CK_ATTRIBUTE(CKA_UNWRAP, true);
aesKeyObject[9] = new CK_ATTRIBUTE(CKA_ENCRYPT, true);
aesKeyObject[10] = new CK_ATTRIBUTE(CKA_DECRYPT, true);
aesKeyObject[11] = new CK_ATTRIBUTE(CKA_TRUSTED, true);
aesKeyObject[12] = new CK_ATTRIBUTE(CKA_ID, 1550);
CK_MECHANISM mech = new CK_MECHANISM(CKM_AES_KEY_GEN);
long newAESKeyHandle = p11.C_GenerateKey(hSession, mech, aesKeyObject);
}catch(Exception e)
{
}
Then you can work with this handle to use newly generated key.
Also the PKCS11 wrapper has methods for wrapping and unwrapping keys which you can use to backup:
public native byte[] C_WrapKey(long hSession,
CK_MECHANISM pMechanism,
long hWrappingKey,
long hKey) throws PKCS11Exception
public native long C_UnwrapKey(long hSession,
CK_MECHANISM pMechanism,
long hUnwrappingKey,
byte[] pWrappedKey,
CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception
Related
I have the following code to extract Private Key
PEMParser parser = new PEMParser(new InputStreamReader(new ByteArrayInputStream(decoded)));
Object object = parser.readObject();
PEMDecryptorProvider provider = new JcePEMDecryptorProviderBuilder()
.build(props.getProperty(KeytoolFlags.KEYPASS.name()).toCharArray());
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
if (object instanceof PEMEncryptedKeyPair) {
KeyPair pair = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(provider));
return loadPublic ? pair.getPublic() : pair.getPrivate();
} else if (object instanceof PEMKeyPair) {
return loadPublic ? converter.getPublicKey(((PEMKeyPair) (object)).getPublicKeyInfo())
: converter.getPrivateKey(((PEMKeyPair) (object)).getPrivateKeyInfo());
} else {
InputDecryptorProvider p2 = new JceOpenSSLPKCS8DecryptorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(props.getProperty(KeytoolFlags.KEYPASS.name()).toCharArray());
return converter.getPrivateKey(((PKCS8EncryptedPrivateKeyInfo) object).decryptPrivateKeyInfo(p2));
}
I would like to get the Public Key from converter when it's JceOpenSSLPKCS8DecryptorProviderBuilder. Is there any way?
Thanks,
The simplest way, although it feels rather ugly to me, is to convert the private key 'back' to one of OpenSSL's 'legacy' forms, which PEMParser is then able to turn into a PEMKeyPair with both halves, from which the public can be selected. Otherwise, the method must be tailored depending on the key algorithm aka type, but can be more efficient which I like better. Here are both options for your consideration:
public static void SO57043669PKCS8_Public_BC (String[] args) throws Exception {
Object p8e = new PEMParser (new FileReader (args[0])).readObject();
// for PKCS8-encrypted result is org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo
PrivateKeyInfo p8i = ((PKCS8EncryptedPrivateKeyInfo)p8e).decryptPrivateKeyInfo(
new JceOpenSSLPKCS8DecryptorProviderBuilder().build(args[1].toCharArray()) );
// or get org.bouncycastle.asn1.pkcs.PrivateKeyInfo directly from PEMParser for PKCS8-clear
PublicKey pub = null;
if( args.length>=3 ){ // the simple way:
PrivateKey prv = new JcaPEMKeyConverter().getPrivateKey(p8i);
PemObject old = new JcaMiscPEMGenerator (prv,null).generate();
StringWriter w1 = new StringWriter();
PemWriter w2 = new PemWriter(w1);
w2.writeObject(old); w2.close();
Object pair = new PEMParser(new StringReader(w1.toString())).readObject();
pub = new JcaPEMKeyConverter().getKeyPair((PEMKeyPair)pair).getPublic();
}else{
ASN1ObjectIdentifier id = p8i.getPrivateKeyAlgorithm().getAlgorithm();
PKCS8EncodedKeySpec p8s = new PKCS8EncodedKeySpec (p8i.getEncoded());
if( id.equals(PKCSObjectIdentifiers.rsaEncryption) ){
// the standard PKCS1 private key format for RSA redundantly includes e
KeyFactory rfact = KeyFactory.getInstance("RSA");
RSAPrivateCrtKey rprv = (RSAPrivateCrtKey) rfact.generatePrivate(p8s);
// or JcaPEMKeyConverter.getPrivateKey does the same thing
pub = /*(RSAPublicKey)*/ rfact.generatePublic(
new RSAPublicKeySpec (rprv.getModulus(), rprv.getPublicExponent()));
}else if( id.equals(X9ObjectIdentifiers.id_dsa) ){
// the apparently ad-hoc format OpenSSL uses for DSA does not include y but it can be computed
KeyFactory dfact = KeyFactory.getInstance("DSA");
DSAPrivateKey dprv = (DSAPrivateKey) dfact.generatePrivate(p8s);
// or JcaPEMKeyConverter.getPrivateKey does the same thing
BigInteger p = dprv.getParams().getP(), q = dprv.getParams().getQ(), g = dprv.getParams().getG();
pub = /*(DSAPublicKey)*/ dfact.generatePublic (
new DSAPublicKeySpec(g.modPow(dprv.getX(),p), p, q, g) );
// warning: naive computation probably vulnerable to sidechannel attack if any
}else if( id.equals(X9ObjectIdentifiers.id_ecPublicKey) ){
// the SECG SEC1 format for EC private key _in PKCS8 by OpenSSL_
// includes []] BITSTR(Q) (but not [0] params which is already in the PKCS8 algid)
org.bouncycastle.asn1.sec.ECPrivateKey eprv = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(p8i.parsePrivateKey());
byte[] eenc = new SubjectPublicKeyInfo (p8i.getPrivateKeyAlgorithm(), eprv.getPublicKey().getOctets()).getEncoded();
KeyFactory efact = KeyFactory.getInstance("EC");
pub = /*(ECPublicKey)*/ KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(eenc));
//}else if maybe others ...
}else throw new Exception ("unknown private key OID " + id);
}
System.out.println (pub.getAlgorithm() + " " + pub.getClass().getName());
}
In addition to the other answer, here's a way to convert Ed25519 private keys to public keys.
Edit: As #tytk notes in the comments, given a BCEdDSAPrivateKey, you can just call getPublicKey(). I am not entirely sure if it's possible to obtain a private EdDSAKey that wouldn't be BCEdDSAPrivateKey, using BC or otherwise, but just in case I'm leaving an alternative codepath that works.
private val bouncyCastleProvider = BouncyCastleProvider()
private val pkcs8pemKeyConverter = JcaPEMKeyConverter().setProvider(bouncyCastleProvider)
fun makeKeyPair(keyReader: Reader, passphrase: CharArray): KeyPair {
var obj = PEMParser(keyReader).readObject()
...
if (obj is PrivateKeyInfo) {
val privateKey = pkcs8pemKeyConverter.getPrivateKey(obj)
when (privateKey) {
is BCEdDSAPrivateKey -> return KeyPair(privateKey.publicKey, privateKey)
is EdDSAKey -> return KeyPair(genEd25519publicKey(privateKey, obj), privateKey)
}
...
}
...
}
private fun genEd25519publicKey(privateKey: EdDSAKey, privateKeyInfo: PrivateKeyInfo): PublicKey {
val privateKeyRaw = ASN1OctetString.getInstance(privateKeyInfo.parsePrivateKey()).octets
val privateKeyParameters = Ed25519PrivateKeyParameters(privateKeyRaw)
val publicKeyParameters = privateKeyParameters.generatePublicKey()
val spi = SubjectPublicKeyInfo(privateKeyInfo.privateKeyAlgorithm, publicKeyParameters.encoded)
val factory = KeyFactory.getInstance(privateKey.algorithm, bouncyCastleProvider)
return factory.generatePublic(X509EncodedKeySpec(spi.encoded))
}
I am trying to digitally sign xml document and verify the signature with the original xml file with public key and signed document. I have a java code for reference. I need to convert java code to C# where I have java code like this:
certList = new ArrayList<X509Certificate>();
certList.add(signerCert);
certStore = new JcaCertStore(certList);
signedDataGenerator = new CMSSignedDataGenerator();
ContentSigner sha2Signer = new JcaContentSignerBuilder("SHA512with" + privateKey.getAlgorithm()).build(privateKey);
ignedDataGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).setDirectSignature(true).build(sha2Signer, signerCert));
signedDataGenerator.addCertificates(certStore);
CMSSignedData sigData = signedDataGenerator.generate(new CMSProcessableFile(inputXmlFile), false);
signedBytes = sigData.getEncoded();
I have converted java code to C# like this:
X509Store my = new X509Store(StoreName.My, StoreLocation.LocalMachine);
my.Open(OpenFlags.ReadOnly);
// Find the certificate we’ll use to sign
RSACryptoServiceProvider csp = null;
foreach (X509Certificate2 cert in my.Certificates)
{
if (cert.Subject.Contains(certSubject))
{
// We found it.
// Get its associated CSP and private key
csp = (RSACryptoServiceProvider)cert.PrivateKey;
}
}
if (csp == null)
{
throw new Exception("oppose no valid application was found");
}
// Hash the data
SHA512Managed sha1 = new SHA512Managed();
UnicodeEncoding encoding = new UnicodeEncoding();
byte[] data = encoding.GetBytes(text);
byte[] hash = sha1.ComputeHash(data);
// Sign the hash
return csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
I am trying to convert it since two days, It is generating sign byte array but not been able to verify. While verifying it is throwing bad hash\r\n error I shall be highly grateful for any assistance. I know I am somewhere wrong in converting the java code to C#. I am able to verify the code but not been able to sign the document
I have generated Signature using System.Security.Cryptography.Pkcs library like this
public static byte[] Sign(byte[] data, X509Certificate2 certificate)
{
if (data == null)
throw new ArgumentNullException("data");
if (certificate == null)
throw new ArgumentNullException("certificate");
// setup the data to sign
ContentInfo content = new ContentInfo(data);
SignedCms signedCms = new SignedCms(content, false);
CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificate);
// create the signature
signedCms.ComputeSignature(signer);
return signedCms.Encode();
}
and verify the signature like this
private static bool VerifySignatures(FileInfo contentFile, Stream signedDataStream)
{
CmsProcessable signedContent = null;
CmsSignedData cmsSignedData = null;
Org.BouncyCastle.X509.Store.IX509Store store = null;
ICollection signers = null;
bool verifiedStatus = false;
try
{
//Org.BouncyCastle.Security.addProvider(new BouncyCastleProvider());
signedContent = new CmsProcessableFile(contentFile);
cmsSignedData = new CmsSignedData(signedContent, signedDataStream);
store = cmsSignedData.GetCertificates("Collection");//.getCertificates();
IX509Store certStore = cmsSignedData.GetCertificates("Collection");
signers = cmsSignedData.GetSignerInfos().GetSigners();
foreach (var item in signers)
{
SignerInformation signer = (SignerInformation)item;
var certCollection = certStore.GetMatches(signer.SignerID);
IEnumerator iter = certCollection.GetEnumerator();
iter.MoveNext();
var cert = (Org.BouncyCastle.X509.X509Certificate)iter.Current;
verifiedStatus = signer.Verify(cert.GetPublicKey());
}
}
catch (Exception e)
{
throw e;
}
return verifiedStatus;
}
It is working for me
I've found this thread: Connecting to SoftHSM java and it works when storing private keys, just like the example.
But I need to store secret keys, such as AES.
Here's my code:
import java.security.*;
import sun.security.pkcs11.*;
import javax.crypto.spec.SecretKeySpec;
public class Main {
public static void main(String[] args) throws Exception {
// Set up the Sun PKCS 11 provider
String configName = "softhsm.cfg";
Provider p = new SunPKCS11(configName);
if (-1 == Security.addProvider(p)) {
throw new RuntimeException("could not add security provider");
}
// Load the key store
char[] pin = "mypin".toCharArray();
KeyStore keyStore = KeyStore.getInstance("PKCS11", p);
keyStore.load(null, pin);
// AES key
SecretKeySpec secretKeySpec = new SecretKeySpec("0123456789ABCDEF".getBytes(), "AES");
Key key = new SecretKeySpec(secretKeySpec.getEncoded(), "AES");
keyStore.setKeyEntry("AA", key, "1234".toCharArray(), null);
keyStore.store(null); //this gives me the exception.
}
}
And this is the softhsm.cfg file:
name = SoftHSM
library = /usr/local/lib/softhsm/libsofthsm.so
slot = 0
attributes(generate, *, *) = {
CKA_TOKEN = true
}
attributes(generate, CKO_CERTIFICATE, *) = {
CKA_PRIVATE = false
}
attributes(generate, CKO_PUBLIC_KEY, *) = {
CKA_PRIVATE = false
}
When executing keyStore.store(null) I'm getting java.security.KeyStoreException Cannot convert to PKCS11 keys
Turns out the Exception occurs with SoftHSMv1. I installed SoftHSMv2, wich you can get using git to download it from GitHub, and use it to store secret keys. Don't download SoftHSMv2 from the OpenDNSsec website because it won't work!!.
Finally I had to change the softhsm.cfg file to point the new library and for some reason I ignore, SoftHSM2 changes the number of the initializated slot, you can verify it using sudo softhsm2-util --show-slots
softhsm.cfg:
name = SoftHSM
library = /usr/local/lib/softhsm/libsofthsm2.so
slot = 498488451
attributes(generate, *, *) = {
CKA_TOKEN = true
}
attributes(generate, CKO_CERTIFICATE, *) = {
CKA_PRIVATE = false
}
attributes(generate, CKO_PUBLIC_KEY, *) = {
CKA_PRIVATE = false
}
My code:
import java.security.*;
import sun.security.pkcs11.*;
import javax.crypto.spec.SecretKeySpec;
public class Main {
public static void main(String[] args) throws Exception {
// Set up the Sun PKCS 11 provider
String configName = "softhsm.cfg";
Provider p = new SunPKCS11(configName);
if (-1 == Security.addProvider(p)) {
throw new RuntimeException("could not add security provider");
}
// Load the key store
char[] pin = "mypin".toCharArray();
KeyStore keyStore = KeyStore.getInstance("PKCS11", p);
keyStore.load(null, pin);
// AES key
SecretKeySpec secretKeySpec = new SecretKeySpec("0123456789ABCDEF".getBytes(), "AES");
Key key = new SecretKeySpec(secretKeySpec.getEncoded(), "AES");
keyStore.setKeyEntry("AA", key, "1234".toCharArray(), null);
keyStore.store(null); //this no longer gives me the exception.
Enumeration<String> aliases = keyStore.aliases();
while(aliases.hasMoreElements()){
String alias = aliases.nextElement();
System.out.println(alias + ": " + keyStore.getKey(alias,"1234".toCharArray()));
}
}
}
Which gives me the output:
AA: SunPKCS11-SoftHSM AES secret key, 16 bits (id 2, token object, not sensitive, unextractable)
If you try to get the key using something like keyStore.getKey("AA", "1234".toCharArray()); you'll get an objet with some attributes of the key but you wont be able to use .getEncoded() to actually get the key itself since it is unextractable.
I've been trying to implement digital signing (CAdES) for PDF files using Portuguese Citizen Card, however I'm having a hard time figuring out the perfectly working solution. Currently I have two sets of code.
First one:
public void signCAdES(...)
{
String pkcs11Config = "name=GemPC" + "\n" + "library=C:\\WINDOWS\\SysWOW64\\pteidpkcs11.dll";
ByteArrayInputStream configStream = new ByteArrayInputStream(pkcs11Config.getBytes());
Provider pkcs11Provider = new sun.security.pkcs11.SunPKCS11(configStream);
//provider_name: SunPKCS11-GemPC
Security.addProvider(pkcs11Provider);
javax.security.auth.callback.CallbackHandler cmdLineHdlr = new DialogCallbackHandler();
KeyStore.Builder builder = KeyStore.Builder.newInstance("PKCS11", pkcs11Provider,
new KeyStore.CallbackHandlerProtection(cmdLineHdlr));
KeyStore ks= builder.getKeyStore();
PdfReader reader = new PdfReader(src);
FileOutputStream os = new FileOutputStream(dest);
PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', new File(tempPath), true);
PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
appearance.setReason(reason);
appearance.setLocation(location);
appearance.setCertificationLevel(level);
String alias = "CITIZEN SIGNATURE CERTIFICATE";
//certificates from electronic card and resources folder
Certificate[] certs = getSignatureCertificatesChain(ks);
PrivateKey pk = (PrivateKey) ks.getKey(alias, null);
ExternalSignature es = new PrivateKeySignature(pk, "SHA-1", pkcs11Provider.getName());
ExternalDigest digest = new BouncyCastleDigest();
MakeSignature.signDetached(appearance, digest, es, certs, null, null, null, 0, MakeSignature.CryptoStandard.CADES);
}
The first one works, however I have a validator given to me that verifies if the signatures of a PDF satisfies the standards, and it seems that one of the attributes is missing (sigining certificate issuer's serial number).
The second one is different, and I have to add the attributes manually, however the generated PDF is corrupted (and then I might need to add the issuer serial attribute too):
private static void signCAdES(byte[] aDocument, PrivateKey aPrivateKey, Certificate[] certChain, String outputPath) {
try {
Security.addProvider(new BouncyCastleProvider());
ArrayList<X509Certificate> certsin = new ArrayList<X509Certificate>();
for (Certificate certChain1 : certChain) {
certsin.add((X509Certificate) certChain1);
}
X509Certificate signingCertificate= certsin.get(0);
MessageDigest dig = MessageDigest.getInstance("SHA-1");
byte[] certHash = dig.digest(signingCertificate.getEncoded());
ESSCertID essCertid = new ESSCertID(certHash);
DERSet set = new DERSet(new SigningCertificate(essCertid));
Attribute certHAttribute = new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate, set);
AttributeTable at = getAttributeTableWithSigningCertificateAttribute(certHAttribute);
CMSAttributeTableGenerator attrGen = new DefaultSignedAttributeTableGenerator(at);
SignerInfoGeneratorBuilder genBuild = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider());
genBuild.setSignedAttributeGenerator(attrGen);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
ContentSigner shaSigner = new JcaContentSignerBuilder("SHA1withRSA").build(aPrivateKey);
SignerInfoGenerator sifGen = genBuild.build(shaSigner, new X509CertificateHolder(signingCertificate.getEncoded()));
gen.addSignerInfoGenerator(sifGen);
JcaCertStore jcaCertStore = new JcaCertStore(certsin);
gen.addCertificates(jcaCertStore);
CMSTypedData msg = new CMSProcessableByteArray(aDocument);
CMSSignedData sigData = gen.generate(msg, false); // false=detached
byte[] encoded = sigData.getEncoded();
ASN1InputStream in = new ASN1InputStream(encoded);
CMSSignedData sigData2 = new CMSSignedData(new CMSProcessableByteArray(aDocument), in);
byte[] encoded2 = sigData2.getEncoded();
FileOutputStream fos = new FileOutputStream(outputPath);
fos.write(encoded2);
// fos.write(encoded);
fos.flush();
fos.close();
} catch (CMSException | IOException | OperatorCreationException | CertificateEncodingException ex) {
log("signCAdES", "Error: " + ex.toString());
}
}
Is there anyone who understands CAdES digital signature using Java? Any help would be appreciated!
The 'issuer-serial' attribute is absent or does not match!
It means that your cades signature has not signed attribute: the signed reference to the signing certificate or that this reference is tampered.
Please check: ETSI TS 101 733 V2.2.1 (2013-04) for more information:
5.7.3 Signing Certificate Reference Attributes
The Signing certificate reference attributes are supported by using either the
ESS signing-certificate attribute or the ESS-signing-certificate-v2 attribute...
I have to create PKCS10 certificate request for RSA keypair stored on cryptocard with access via PKCS11 interface. The thing is that I can't use standard RSA algorithms in PKCS10 creation process and I can't get private key from cryptocard, so crypto operations should be done on cryptocard side. How can I prepare (maybe manually) PKCS10 request using PKCS11 interface for signing?
#Edit
Now I have an error like this:
Exception in thread "main" java.security.ProviderException: Initialization failed
at sun.security.pkcs11.P11Signature.initialize(P11Signature.java:310)
at sun.security.pkcs11.P11Signature.engineInitSign(P11Signature.java:391)
at java.security.Signature$Delegate.engineInitSign(Signature.java:1127)
at java.security.Signature.initSign(Signature.java:511)
at pkcs11.Main.stworzPkcs10(Main.java:65)
at pkcs11.Main.main(Main.java:53)
Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR
at sun.security.pkcs11.wrapper.PKCS11.C_SignInit(Native Method)
at sun.security.pkcs11.P11Signature.initialize(P11Signature.java:302)
... 5 more
Java Result: 1
and code:
String zawartoscPlikuKonfiguracyjnego = new String(
"name=PKCS11\n" +
"library=" + sciezkaDoBibliotekiPkcs11);
FileOutputStream plikKonfiguracyjny = new FileOutputStream("pkcs11.cfg");
plikKonfiguracyjny.write(zawartoscPlikuKonfiguracyjnego.getBytes());
plikKonfiguracyjny.close();
File test = new File("pkcs11.cfg");
dostawcaPkcs11 = new SunPKCS11("pkcs11.cfg");
Security.addProvider(dostawcaPkcs11);
interfejsPkcs11 = KeyStore.getInstance("PKCS11",dostawcaPkcs11);
pin = new JPasswordField();
JOptionPane.showConfirmDialog(null, pin, "Podaj pin do tokena", JOptionPane.OK_CANCEL_OPTION);
interfejsPkcs11.load(null, pin.getPassword());
Key kluczPrywatny = null;
Key kluczPubliczny = null;
Enumeration<String> aliasy = interfejsPkcs11.aliases();
while(aliasy.hasMoreElements()) {
String alias = aliasy.nextElement();
if(interfejsPkcs11.isKeyEntry(alias)) {
kluczPrywatny = interfejsPkcs11.getKey(alias, pin.getPassword());
} else {
kluczPubliczny = interfejsPkcs11.getCertificate(alias).getPublicKey();
}
}
PKCS10 pkcs10 = new PKCS10((PublicKey) kluczPubliczny );
Signature sygnatura = Signature.getInstance("SHA1WithRSA", dostawcaPkcs11);
sygnatura.initSign((PrivateKey) kluczPrywatny);
X500Name nazwaX500 = new X500Name("Certyfikat testowy", "Developer", "Developer", "Warszawa", "Mazovia", "PL");
pkcs10.encodeAndSign(nazwaX500, sygnatura);
I would recommend you try using the Sun PKCS#11 provider. You will need to follow the documentation to understand how to configure the provider to use the DLL supplied by your cryptocard supplier. (Also worth asking them their recommended approach to accessing the cryptocard from Java).
Once you have this working, you should be able to load your public and private keys from a keystore (again see the docs for how this works). Finally, you can use the JCE libraries to produce the signing request:
String CN = "Mr Foo";
String OU = "Foo Department";
String O = "Foo Ltd.";
String L = "Foosville";
String S = "Foouisiana";
String C = "GB";
PublicKey publicKey = //... load public key from keystore
PrivateKey privateKey = //... load private key from keystore
PKCS10 pkcs10 = new PKCS10(publicKey);
Signature signature = Signature.getInstance("SHA1WithRSA"); // or whatever
signature.initSign(privateKey);
X500Name x500Name = new X500Name(CN, OU, O, L, S, C);
pkcs10.encodeAndSign(new X500Signer(signature, x500Name));
try (ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs)) {
pkcs10.print(ps);
byte[] c = bs.toByteArray(); // <-- this is it! (save to disk maybe?)
}