I am trying to send a Certificate Signing Request from an Android device to a server. The server is working properly with iOS devices and follows a SCEP procedure with OpenSSL.
So here is my problem :
I can send the signed enveloped CSR but the server can't read the enveloped CSR. I have the following error from the server :
pki.rb:26:in initialize: Could not parse the PKCS7: header too long (ArgumentError)
Related ruby server code :
#receive object and put it in object data
[...]
# Verify Input Data
p7sign = OpenSSL::PKCS7.new(data)
store = OpenSSL::X509::Store.new
p7sign.verify(nil, store, nil, OpenSSL::PKCS7::NOVERIFY)
signers = p7sign.signers
# Encrypted data (LINE 26 :)
p7enc = OpenSSL::PKCS7.new(p7sign.data)
# Certificate Signing Request
csr = p7enc.decrypt(ssl.key, ssl.certificate)
# Signed Certificate
request = OpenSSL::X509::Request.new(csr)
Java Code (Android) :
I am using Bouncy Castle to generate the CSR and Volley (Google) to send it.
Main :
//Generate PEM formated CSR
byte[] pemCsr = getPemFromCsr(generateCSR());
//Envelop it in a PKCS#7 object
byte[] envelopedData = getDerFromCMSEnvelopedData(envelopData(pemCsr));
//Sign it in a PKCS#7 object
byte[] signedData = getDerFromCMSSignedData(signData(envelopedData));
sendCsrRequest(signedData);
CSR :
//Generate the CSR
private static PKCS10CertificationRequest genrateCertificationRequest(){
// Build the CN for the cert we
X500NameBuilder nameBld = new X500NameBuilder(BCStyle.INSTANCE);
nameBld.addRDN(BCStyle.CN, "cn");
nameBld.addRDN(BCStyle.O, "o");
nameBld.addRDN(BCStyle.NAME, "name");
X500Name principal = nameBld.build();
// Generate the certificate signing request (csr = PKCS10)
String sigAlg = "SHA1withRSA";
JcaContentSignerBuilder csb = new JcaContentSignerBuilder(sigAlg);
ContentSigner cs = csb.build(privateKey);
DERPrintableString password = new DERPrintableString("mychallenge");
PKCS10CertificationRequestBuilder crb = new JcaPKCS10CertificationRequestBuilder(principal, publicKey);
crb.addAttribute((ASN1ObjectIdentifier) PKCSObjectIdentifiers.pkcs_9_at_challengePassword, password);
PKCS10CertificationRequest csr = crb.build(cs);
return csr;
}
//Envelop the CSR
private static CMSEnvelopedData envelopData(byte[] pemCsr) {
CMSTypedData msg = new CMSProcessableByteArray(pemCsr);
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(x509Certificate).setProvider("BC"));
CMSEnvelopedData ed = edGen.generate(msg,new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider("BC").build());
return ed;
}
//Sign the enveloped CSR
private static CMSSignedData signData(byte[] data){
ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privateKey);
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(signer, (X509Certificate) x509Certificate));
CMSTypedData cmsdata = new CMSProcessableByteArray(data);
CMSSignedData signedData = generator.generate(cmsdata, true);
return signedData;
}
I have other code ready to paste (the Volley request, the utils converter) but maybe it is enough for the moment.
SCEP is already working with iOS devices, so the server is clean.
Ruby can create the signed PKCS#7 so I guess that my signing step is OK.
But if I send an empty signed PKCS#7, I surprisingly have the same error.
Thanks in advance for any help.
It seems that the ASN1 of the envelop isn't correct for OpenSSL.
In parallel, Google Volley automatically adds "\n" in the response which also raises problems.
Related
Does anyone know what will be the equivalent of following command (GnuPG 2.17.2) in bouncy castle in Java?
gpg -e -r "recipient" --output output.gpg input.zip
Create a certificate and private key
public static byte[] encryptData(byte[] data, X509Certificate encryptionCertificate) throws CertificateEncodingException, CMSException, IOException {
byte[] encryptedData = null;
if (null != data && null != encryptionCertificate) {
CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator
= new CMSEnvelopedDataGenerator();
JceKeyTransRecipientInfoGenerator jceKey
= new JceKeyTransRecipientInfoGenerator(encryptionCertificate);
cmsEnvelopedDataGenerator.addRecipientInfoGenerator(transKeyGen);
CMSTypedData msg = new CMSProcessableByteArray(data);
OutputEncryptor encryptor
= new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC)
.setProvider("BC").build();
CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator
.generate(msg,encryptor);
encryptedData = cmsEnvelopedData.getEncoded();
}
return encryptedData;}
Create a JceKeyTransRecipientInfoGenerator object using the recipient's certificate.
Then Create a new CMSEnvelopedDataGenerator object and added the recipient information generator into it.
Then use the JceCMSContentEncryptorBuilder class to create an OutputEncrytor object, using the AES CBC algorithm.
The encryptor is used later to generate a CMSEnvelopedData object that encapsulates the encrypted message.
Finally, the encoded representation of the envelope is returned as a byte array.
Get the final Byte array written to a file.
This is my code which generated certificate.
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(2048);
pair = gen.generateKeyPair();
privateKey = pair.getPrivate();
publicKey = pair.getPublic();
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
X509v3CertificateBuilder builder = new X509v3CertificateBuilder(subjectDN, new BigInteger(serialNumber + ""),
startDate, endDate, subjectDN,
publicKeyInfo);
ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(privateKey);
cert = new JcaX509CertificateConverter().getCertificate(builder.build(signer));
When I upload it and try to set webhook via setWebhook API method, It fails.
{"ok":false,"error_code":400,"description":"Bad webhook: Failed to set custom cert file"}
Can someone tell me what I'm missing?
EDIT. This is my public key in PEM format:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqA2BQC0cOGVns9USxRwk
2PQHtk3lfDqEdhmQjiW6U0RA102IbLx2ALizkegO9TwjFszynjRuq6KlQT4ctvEy
XyKpb9tMF5tRg2haDDEfyCfpKxuwQfjzYLLp+RqxLMsAngMaE3UwM6lyo9jYUHxD
sfQgUWkg6vCJ9b52/IAFYsuq14//J1ZrHRlYBnGImOroMWwLBmMZVmTxeB/QyTDc
gbj/uBbOKTckk7jchAxtO/PRVZ5nW2PWxAeE0FAtwhHHXTfwINqkcEmk21/jlpvT
GTHkkoxEl+BptvIKqrgSdvoTbHSVpn9U6ZJTV8ZVC46xcjiD/eFxr+dl3oZAjG6N
5wIDAQAB
-----END PUBLIC KEY-----
I send this to server using multi part.
I had the same problem. The public key would be enough for Telegram. Make sure you attach the certificate as binary and provide a filename.
final byte[] pemFileAsBytes = pemFileAsString.getBytes(StandardCharsets.UTF_8);
final HttpEntity httpEntity = MultipartEntityBuilder.create()
.addTextBody("url", webhookUrl)
.addBinaryBody("certificate", pemFileAsBytes, ContentType.APPLICATION_OCTET_STREAM, "telegram.pem")
.build();
The API for the webhook says:
... the pem file should only contain the public key (including BEGIN and END portions)
However, all(!) tutorials they offer generates a certificate, not a blank public key.
Try parsing your whole certificate as PEM and feeding it to the webhook:
PrintWriter writer = new PrintWriter("cert.pem", "UTF-8");
JcaMiscPEMGenerator pemGen = new JcaMiscPEMGenerator(cert);
JcaPEMWriter pemWriter = new JcaPEMWriter(writer);
pemWriter.writeObject(pemGen);
pemWriter.close();
I have been looking for the past few days for a solution on my Problem and couldn't find anything. I am missing something in my Code but i cant figure out what :( Somehow when I sign my PKCS#10 the chain is broken.
Basically i have a server and a client. I want to have the client send a CSR to the server and the server signs it so they can communicate. Now i did set up a PKCS#12 with BouncyCastle for the Client and i did set up a RootCertificate for the Server (again with BouncyCastle, which is in my understanding just a PKCS#12 with the extension to be able to sign Certificates)
In Code it looks like this:
Provider BC = new BouncyCastleProvider();
Security.addProvider(BC);
//create KeyPair
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
kpGen.initialize(2048, new SecureRandom());
pair = kpGen.generateKeyPair();
//building groundbase for certificate
X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
builder.addRDN(BCStyle.CN, commonName);
builder.addRDN(BCStyle.OU, organizationalUnit);
builder.addRDN(BCStyle.O, organization);
builder.addRDN(BCStyle.L, city);
builder.addRDN(BCStyle.ST, state);
builder.addRDN(BCStyle.C, country);
Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24); //Yesterday
Date notAfter = new Date(System.currentTimeMillis() + 1000L * 365L * 24L * 60L * 60L); //in a year
BigInteger serial = BigInteger.valueOf(new SecureRandom().nextLong());
//creating a self-signed certificate from information in builder
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(builder.build(),
serial, notBefore, notAfter, builder.build(), pair.getPublic());
//The next line will make the difference between a Certificate and a Ca Certificate
certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
ContentSigner sigGen = new JcaContentSignerBuilder(").setProvider(BC).build(pair.getPrivate());
X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen));
Now i create a CSR for the Client (Client keystore has the just created PKCS#12 at first position):
String alias = keystore.aliases().nextElement();
X509Certificate cert = (X509Certificate) keystore.getCertificate(alias);
X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
//builder for the PKCS10
PKCS10CertificationRequestBuilder requestBuilder = new JcaPKCS10CertificationRequestBuilder(x500name, cert.getPublicKey());
//algorithm identifier
DefaultSignatureAlgorithmIdentifierFinder sigAlgFinder = new DefaultSignatureAlgorithmIdentifierFinder();
DefaultDigestAlgorithmIdentifierFinder digAlgFinder = new DefaultDigestAlgorithmIdentifierFinder();
AlgorithmIdentifier sigAlgId = sigAlgFinder.find("SHA512WithRSA");
digAlgFinder.find(sigAlgId);
//content Signer
JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder("SHA512WithRSA");
//and build the Cert
ContentSigner signer = contentSignerBuilder.build((PrivateKey) keystore.getKey(alias, password));
PKCS10CertificationRequest req = requestBuilder.build(signer);
JcaPKCS10CertificationRequest req2 = new JcaPKCS10CertificationRequest(req.getEncoded()).setProvider("BC");
I send this JcaPKCS10CertificationRequest encoded over the network. The Server gets it and creates his CA Certificate and now has to sign the PKCS#10 but i am missing something here because he is not including the chain. The Certificate he is creating has the information about the issuer and BasicConstraints but the certification path is only including the Clients Certificate and NOT the Certificate of the Server so it is not trustworthy since the chain is broken.
This is what i do (Server Keystore has the CA Certificate at position 0, CSR is the JcaPKCS10CertificationRequest):
String alias = keystore.aliases().nextElement();
// PKCS#12 Root Certificate
X509Certificate cert = (X509Certificate) keystore.getCertificate(alias);
// generated Serial
BigInteger serial = BigInteger.valueOf(new SecureRandom().nextLong());
//identify algorithm
AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA512WithRSA");
AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find( sigAlgId );
JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(cert, serial, cert.getNotBefore(), cert.getNotAfter(),
CSR.getSubject(), CSR.getPublicKey());
certGen.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(cert));
certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
certGen.addExtension(Extension.subjectKeyIdentifier, true, extUtils.createSubjectKeyIdentifier(inputCSR.getPublicKey()));
certGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.nonRepudiation));
ContentSigner signer = new JcaContentSignerBuilder(sigAlgName).setProvider("BC").build((PrivateKey)keystore.getKey(alias, password));
X509CertificateHolder holder = certGen.build(signer);
X509Certificate signedCert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder);
signedCert.verify(cert.getPublicKey());
JcaPEMWriter pemWriter = new JcaPEMWriter(new FileWriter(new File("cer.cer")));
pemWriter.writeObject(signedCert);
pemWriter.writeObject(cert);
pemWriter.close();
Now as i said the generated File "cer.cer" has not the Chain in it. How can i add the chain? Can i then send that signedCert back to the client and it can be used in a ssl handshake?
To add the chain, this worked for me
After X509CertificateHolder holder = certGen.build(signer);
byte[] certencoded = holder.toASN1Structure().getEncoded();
ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").build(caPrivateKkey);
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(signer, cacert));
generator.addCertificate(new X509CertificateHolder(certencoded));
generator.addCertificate(new X509CertificateHolder(cacert.getEncoded()));
CMSTypedData content = new CMSProcessableByteArray(certencoded);
CMSSignedData signeddata = generator.generate(content, true);
byte certificateP7b[] = signedData.getEncoded();
With this code you get a Certificate with the full chain in PCKS#7 format. If you prefer to work with X509 format
public static List<X509Certificate> p7BToX509(byte signedCert[]) throws CertificateException{
ByteArrayInputStream is = new ByteArrayInputStream( signedCert);
CertificateFactory cf = CertificateFactory.getInstance( "X.509" );
ArrayList<X509Certificate> certificates = new ArrayList<X509Certificate>();
Iterator i = cf.generateCertificates( is ).iterator();
while ( i.hasNext() ){
X509Certificate c = (X509Certificate)i.next();
certificates.add(c);
}
return certificates;
}
This is the public certificate. In your client you should have the private key. These are all elements you need to perform and ssl handshake
Here what I have so far generating a Certificate for a User
try {
Security.addProvider(new BouncyCastleProvider()); // adding provider
// to
String pathtoSave = "D://sureshtest.cer";
KeyPair keyPair = generateKeypair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
X509Certificate trustCert = createCertificate(null, "CN=CompanyName",
"CN=Owner", publicKey, privateKey);
java.security.cert.Certificate[] outChain = { trustCert, };
trustCert.checkValidity();
KeyStore outStore = KeyStore.getInstance("PKCS12");
outStore.load(null, null);
outStore.setKeyEntry("my own certificate", privateKey,
"admin123".toCharArray(), outChain);
OutputStream outputStream = new FileOutputStream(pathtoSave);
outStore.store(outputStream, "admin123".toCharArray());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
The above code generate a certificate with a private and public key.
Now I want to sign that certificate with a signing certificate I've been issued by a certificate authority (CA). After that I'll grant that certificate to user.
I got some input from here and it seems that is not the required answer with my case.
No need for a full implementation, just a valid procedure or some hints will greatly help.
You need to generate a CSR so you can invoke the code from Sign CSR using Bouncy Castle which is using the BC API. Add this to your code above:
final PKCS10 request = new PKCS10(publicKey);
final String sigAlgName = "SHA1WithRSA"; // change this to SHA1WithDSA if it's a DSA key
final Signature signature = Signature.getInstance(sigAlgName);
signature.initSign(privateKey);
final X500Name subject = new X500Name(trustCert.getSubjectDN().toString());
final X500Signer signer = new X500Signer(signature, subject);
// Sign the request and base-64 encode it
request.encodeAndSign(signer);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream writer = new PrintStream(baos);
request.print(writer);
// Remove -----BEGIN NEW CERTIFICATE REQUEST----- and -----END NEW CERTIFICATE REQUEST-----
final String requestBase64 = new String(baos.toByteArray());
String withoutTags = requestBase64.substring(41);
withoutTags = withoutTags.substring(0, withoutTags.length() - 39);
// org.bouncycastle.pkcs.PKCS10CertificationRequestHolder
final PKCS10CertificationRequest holder = new PKCS10CertificationRequest(Base64.decode(withoutTags));
// Feed this into https://stackoverflow.com/questions/7230330/sign-csr-using-bouncy-castle
I have an X509CertificateObject, a matching RSAPublicKey and managed to create a byte array containing a valid digital certificate for some message object also as a byte array.
Unfortunately the system I'm building upon only accepts CMSSignedData objects as input.
How do I convert my basic building blocks into such a valid CMSSignedData object?
Background: I'm experimenting with Java Bouncy Castle RSA blind signatures according to this example (digest is SHA512) and need to feed the result into the standard signature processing.
First, you'll probably want to sign your data with a private key. The idea being that the signature should be something only you can create. One you get that the rest should be as follows:
X509Certificate signingCertificate = getSigningCertificate();
//The chain of certificates that issued your signing certificate and so on
Collection<X509Certificate> certificateChain = getCertificateChain();
PrivateKey pk = getPrivateKey();
byte[] message = "SomeMessage".getBytes();
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
certificateChain.add(signingCertificate);
generator.addCertificates(new CollectionStore(certificateChain));
JcaDigestCalculatorProviderBuilder jcaDigestProvider = new JcaDigestCalculatorProviderBuilder();
jcaDigestProvider.setProvider(new BouncyCastleProvider());
JcaSignerInfoGeneratorBuilder singerInfoGenerator = new JcaSignerInfoGeneratorBuilder(jcaDigestProvider.build());
AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
AsymmetricKeyParameter privateKeyParam = PrivateKeyFactory.createKey(pk.getEncoded());
ContentSigner cs = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyParam);
SignerInfoGenerator sig = singerInfoGenerator.build(cs, signingCertificate);
generator.addSignerInfoGenerator(sig);
CMSSignedData data = generator.generate(new CMSProcessableByteArray(message), true);