Read Original Data from Signed content java - java

I want to extract original data from signed content.
In the following code, the signed data is "CMSSignedData signed"
I found several similar answers from the StackOverflow, but all the answers cannot
state how to extract original data from signed content.
regards
package chapter9;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.*;
import java.util.Arrays;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.cms.CMSProcessable;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
/**
* Example of generating a detached signature.
*/
public class SignedDataExample
extends SignedDataProcessor
{
public static void main(String[] args)
throws Exception
{
KeyStore credentials = Utils.createCredentials();
PrivateKey key = (PrivateKey)credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD);
Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS);
CertStore certsAndCRLs = CertStore.getInstance("Collection",
new CollectionCertStoreParameters(Arrays.asList(chain)), "BC");
X509Certificate cert = (X509Certificate)chain[0];
// set up the generator
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
gen.addSigner(key, cert, CMSSignedDataGenerator.DIGEST_SHA256);
gen.addCertificatesAndCRLs(certsAndCRLs);
// create the signed-data object
CMSProcessable data = new CMSProcessableByteArray("Hello World!".getBytes());
CMSSignedData signed = gen.generate(data, "BC");
// recreate
signed = new CMSSignedData(data, signed.getEncoded());
//extract public key
CertStore cs = signed.getCertificatesAndCRLs("Collection", "BC");
//signed.signedContent
//signed.g
CMSProcessable S = signed.getSignedContent();
String aaa = S.getContent().toString();
//byte[] K = Base64.decodeBase64((S.getContent()).toString());
//
//String K = Base64.decodeBase64(S.getContent());
//BASE64Decoder.decoder.decodeBuffer()
//
//byte[] array = asString.getBytes("UTF8");
//String s = new String(array, "UTF8");
// verification step
X509Certificate rootCert = (X509Certificate)credentials.getCertificate(Utils.ROOT_ALIAS);
if (isValid(signed, rootCert))
{
System.out.println("verification succeeded");
//System.out.println(K);
//String asString = new String((byte[])data.getContent());
//String asString1 = new String(cs.toString());
//System.out.println(asString);
//System.out.println(asString1);
//System.out.println(aaa);
}
else
{
System.out.println("verification failed");
}
}
}

You need to use String aaa = new String(s); instead of String aaa = S.getContent().toString(); although you should also specify an encoding, e.g. String aaa = new String(s, Charset.forName("UTF-8"));. Please do the same for your toBytes() methods.

Use new String((byte[])S.getContent()); to get the original content

Related

XML Signature remote

We need to send a hash / digest of an XML file to a remote signing service.
The signing service returns a PKCS#7 response. This includes the signature and the short-lived-x509 certificate that was used.
Question: what is the easiest solution to apply the information from the PKCS#7 to the XML file so that it is correctly signed? I am looking for an example (Plain Java or Apache Santuario).
Update:
This is the code used for signing (xml-dsig) an XML with Apache Santuario given a local keystore:
package test.signer.signer;
import org.apache.commons.io.IOUtils;
import org.apache.xml.security.Init;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.signature.XMLSignature;
import org.apache.xml.security.transforms.Transforms;
import org.apache.xml.security.utils.Constants;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
/**
* from: https://stackoverflow.com/a/15911581/5658642
*/
public class CreateSignature
{
private static final String PRIVATE_KEY_ALIAS = "sgw-sign-client-keystore";
private static final String PRIVATE_KEY_PASS = "password";
private static final String KEY_STORE_PASS = "";
private static final String KEY_STORE_TYPE = "JKS";
public static void main(String... unused) throws Exception
{
final InputStream fileInputStream = Files.newInputStream(Paths.get("unsigned_DEV.xml"));
try
{
output(signFile(fileInputStream, new File("sgw-sign-client-keystore.jks")), "signed-test.xml");
} finally
{
IOUtils.closeQuietly(fileInputStream);
}
}
public static ByteArrayOutputStream signFile(InputStream xmlFile, File privateKeyFile) throws Exception
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xmlFile);
Init.init();
final KeyStore keyStore = loadKeyStore(privateKeyFile);
final XMLSignature sig = new XMLSignature(doc, null, XMLSignature.ALGO_ID_SIGNATURE_RSA);
doc.getDocumentElement().appendChild(sig.getElement());
final Transforms transforms = new Transforms(doc);
transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
// TODO replace with external signature
final Key privateKey = keyStore.getKey(PRIVATE_KEY_ALIAS, PRIVATE_KEY_PASS.toCharArray());
final X509Certificate cert = (X509Certificate) keyStore.getCertificate(PRIVATE_KEY_ALIAS);
sig.addKeyInfo(cert);
sig.addKeyInfo(cert.getPublicKey());
sig.sign(privateKey);
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(doc));
return outputStream;
}
private static KeyStore loadKeyStore(File privateKeyFile) throws Exception
{
final InputStream fileInputStream = Files.newInputStream(privateKeyFile.toPath());
try
{
final KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
keyStore.load(fileInputStream, null);
return keyStore;
} finally
{
IOUtils.closeQuietly(fileInputStream);
}
}
private static void output(ByteArrayOutputStream signedOutputStream, String fileName) throws IOException
{
final OutputStream fileOutputStream = Files.newOutputStream(Paths.get(fileName));
try
{
fileOutputStream.write(signedOutputStream.toByteArray());
fileOutputStream.flush();
} finally
{
IOUtils.closeQuietly(fileOutputStream);
}
}
}
This works so far. I now must replace the local keystore with a "remote keystore". The remote signing service takes a digest / hash and signs it. The response is a valid PKCS#7, which contains the certificate and the signature.
I am able to extract both with the following code (based on CMSSignedData from BouncyCastle):
String hashB64 = Base64.getEncoder().encodeToString(digest);
byte[] pkcs7Signature = remoteServiceClientService.sign(hashB64);
CMSSignedData cms = null;
try
{
cms = new CMSSignedData(pkcs7Signature);
SignerInformationStore signers = cms.getSignerInfos();
Collection<SignerInformation> c = signers.getSigners();
for (SignerInformation signer : c) {
// this collection will contain the signer certificate, if present
Collection<X509CertificateHolder> signerCol = cms.getCertificates().getMatches(signer.getSID());
SIG_CERT = new JcaX509CertificateConverter().getCertificate(signerCol.stream().findFirst().get());
}
List<byte[]> signatures = cms.getSignerInfos().getSigners().stream().map(SignerInformation::getSignature)
.collect(Collectors.toList());
byte[] pkcs1Signature = signatures.get(0);
SOPLogger.log("Plain Signature", pkcs1Signature);
return pkcs1Signature;
} catch (CMSException e)
{
throw new RuntimeException(e);
} catch (CertificateException e)
{
throw new RuntimeException(e);
}
I have no idea how to apply the extracted information instead of using a local keystore and are happy to try any hints.

Apple Pay Payment Token Decryption in Java

I am trying to decrypt the data field inside an Apple Pay Payment Token using ECC algorithm in Java on the server side. How can I implement it?
I've been searching for such an implementation in Java for quite a while and I couldn't find one. Instead, I've found an implementation using Bouncy Castle C# library to decrypt the token:
https://github.com/chengbo/ApplePayAndroidPayDecryption
Although there is also an Bouncy Castle library in Java, but I've found some difference in the implementation between the C# one and the Java one, which lead to the failure of decryption when I try to code in accordance with the C# implementation above.
I've generated my certificate in Apple Dev Center and I'm quite sure that the certificate file needed during the process of decrytion is correct.
Has anyone succeeded in decrypting the token in Java? Any help is appreciated, Thanks a lot!
Here is the key part of the return message from Apple when I did a test payment:
passKit={"version":"EC_v1","data":"AK7UZehTHQRXYzgPCD5ijZfloc9ZfUjAutl+7v/83V7U6YjsWSrBVzILQlp2xLP4E4QXxRwadIh0Y9Vg6297BV2ljginDwoR5nneEIQP6fNCXYwll5hUYYlL0ZO7pD/8KXStAh8pnOAyFtEVrDqIRCWZbftzdsAi76qFMXd3Z2bRSjl5zrt8Qfua6Nu1b3MNNVlPQVMJsskEQFncnViNLDkRulgt5WezVF8N1m62nEqminLBF7m+36/pLi0t9JTfqQ0qNYahczAzyyCJhABkXRXXf9iF3YJ77gBD9mBFRVrePPNW0PnJyoQPv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hkjOPQQDAjAvBgkqhkiG9w0BCQQxIgQgi0pw8YTdD5wAw9Wct6Io9DQGiB1iXyGcK9XCWnSu/08wCgYIKoZIzj0EAwIERzBFAiEA+H89sz2Jo8GPM86s7sZ7nQ1RKu/R9I0fkkRBclcppFICIGJbrR764YuHK7ptg9Ch50muHKEuYUa0BjsVhtgCgJvyAAAAAAAA","header":{"ephemeralPublicKey":"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFnF0WIB3GTpyaP7rgW0kzUMgqfwsTecb7/JrSQXZSuILCBPBs2YQQXFfIHNYtFFMzMTY24/tgbolbKjkmIUwIw==","applicationData":"5cd2d027aa6372ea5420770272ef47a596e60f4299c16c6591c3e7e532208394","publicKeyHash":"sRANn6djBkx5m//vTDU6HFOX4j1Nn/X4bNlgxJYRZgo=","transactionId":"947a5fc21adcc692bd204fa4e1a7a4f83ab8383283f3fa46b204b514559adede"}}
This Code(JAVA) will decrypt the ApplePay token. For this code to work convert the certificate file to JKS(retrieve merchant ID) and pk8(private key) formates.
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.bouncycastle.asn1.ASN1UTCTime;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.cms.CMSAttributes;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Store;
import org.bouncycastle.util.encoders.Hex;
import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import static org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME;
import java.io.*;
import java.nio.charset.Charset;
import java.security.*;
import java.security.cert.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;
public class ApplePayDecrypt {
public static final String MERCHANT_ID = "merchant.Id";
private static KeyStore keyStore;
private static PrivateKey merchantPrivateKey;
static {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
}
public static AppleDecryptData decrypt(TokenData tokenData) {
try {
// Load merchant private key
byte[] merchantbyte = IOUtils.toByteArray(Application.class.getResource("/apple_pay.pk8"));
String key = new String(merchantbyte);
key = key.replace("-----BEGIN PRIVATE KEY-----", "");
key = key.replace("-----END PRIVATE KEY-----", "");
key = key.replaceAll("\\s+", "");
byte[] merchantPrivateKeyBytes = Base64.decodeBase64(key);
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(merchantPrivateKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("EC", PROVIDER_NAME);
merchantPrivateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
// Load Apple root certificate
keyStore = KeyStore.getInstance("BKS");
keyStore.load(GoSecureApplication.class.getResourceAsStream("/appleCA-G3"), "apple123".toCharArray());
return unwrap(tokenData);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#SuppressWarnings({ "unused", "unchecked" })
public static AppleDecryptData unwrap(TokenData tokenData) throws Exception {
// Merchants should use the 'version' field to determine how to verify and
// decrypt the message payload.
// At this time the only published version is 'EC_v1' which is demonstrated
// here.
String version = tokenData.version;
byte[] signatureBytes = Base64.decodeBase64(tokenData.signature);
byte[] dataBytes = Base64.decodeBase64(tokenData.data);
// JsonObject headerJsonObject =
// jsonObject.get(PAYMENT_HEADER).getAsJsonObject();
byte[] transactionIdBytes = Hex.decode(tokenData.header.transactionId);
byte[] ephemeralPublicKeyBytes = Base64.decodeBase64(tokenData.header.ephemeralPublicKey);
// Merchants that have more than one certificate may use the 'publicKeyHash'
// field to determine which
// certificate was used to encrypt this payload.
byte[] publicKeyHash = Base64.decodeBase64(tokenData.header.publicKeyHash);
// Application data is a conditional field, present when the merchant has
// supplied it to the iOS SDK.
byte[] applicationDataBytes = null;
byte[] signedBytes = ArrayUtils.addAll(ephemeralPublicKeyBytes, dataBytes);
signedBytes = ArrayUtils.addAll(signedBytes, transactionIdBytes);
signedBytes = ArrayUtils.addAll(signedBytes, applicationDataBytes);
CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(signedBytes), signatureBytes);
// Check certificate path
Store<?> certificateStore = signedData.getCertificates();
List<X509Certificate> certificates = new ArrayList<X509Certificate>();
JcaX509CertificateConverter certificateConverter = new JcaX509CertificateConverter();
certificateConverter.setProvider(PROVIDER_NAME);
for (Object o : certificateStore.getMatches(null)) {
X509CertificateHolder certificateHolder = (X509CertificateHolder) o;
certificates.add(certificateConverter.getCertificate(certificateHolder));
}
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", PROVIDER_NAME);
CertPath certificatePath = certificateFactory.generateCertPath(certificates);
PKIXParameters params = new PKIXParameters(keyStore);
params.setRevocationEnabled(false);
// TODO: Test certificate has no CRLs. Merchants must perform revocation checks
// in production.
// TODO: Verify certificate attributes per instructions at
// https://developer.apple.com/library/ios/documentation/PassKit/Reference/PaymentTokenJSON/PaymentTokenJSON.html#//apple_ref/doc/uid/TP40014929
CertPathValidator validator = CertPathValidator.getInstance("PKIX", PROVIDER_NAME);
PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(certificatePath, params);
System.out.println(result);
// Verify signature
SignerInformationStore signerInformationStore = signedData.getSignerInfos();
boolean verified = false;
for (Object o : signerInformationStore.getSigners()) {
SignerInformation signer = (SignerInformation) o;
Collection<?> matches = certificateStore.getMatches(signer.getSID());
if (!matches.isEmpty()) {
X509CertificateHolder certificateHolder = (X509CertificateHolder) matches.iterator().next();
if (signer.verify(
new JcaSimpleSignerInfoVerifierBuilder().setProvider(PROVIDER_NAME).build(certificateHolder))) {
DERSequence sequence = (DERSequence) signer.getSignedAttributes().get(CMSAttributes.signingTime)
.toASN1Primitive();
DERSet set = (DERSet) sequence.getObjectAt(1);
ASN1UTCTime signingTime = (ASN1UTCTime) set.getObjectAt(0).toASN1Primitive();
// Merchants can check the signing time of this payment to determine its
// freshness.
System.out.println("Signature verified. Signing time is " + signingTime.getDate());
verified = true;
}
}
}
if (verified) {
// Ephemeral public key
KeyFactory keyFactory = KeyFactory.getInstance("EC", PROVIDER_NAME);
PublicKey ephemeralPublicKey = keyFactory.generatePublic(new X509EncodedKeySpec(ephemeralPublicKeyBytes));
// Key agreement
String asymmetricKeyInfo = "ECDH";
KeyAgreement agreement = KeyAgreement.getInstance(asymmetricKeyInfo, PROVIDER_NAME);
agreement.init(merchantPrivateKey);
agreement.doPhase(ephemeralPublicKey, true);
byte[] sharedSecret = agreement.generateSecret();
byte[] derivedSecret = performKDF(sharedSecret, extractMerchantIdFromCertificateOid());
// Decrypt the payment data
String symmetricKeyInfo = "AES/GCM/NoPadding";
Cipher cipher = Cipher.getInstance(symmetricKeyInfo, PROVIDER_NAME);
SecretKeySpec key = new SecretKeySpec(derivedSecret, cipher.getAlgorithm());
IvParameterSpec ivspec = new IvParameterSpec(new byte[16]);
cipher.init(Cipher.DECRYPT_MODE, key, ivspec);
byte[] decryptedPaymentData = cipher.doFinal(dataBytes);
// JSON payload
String data = new String(decryptedPaymentData, "UTF-8");
// System.out.println(data);
AppleDecryptData decryptDat = ObjMapper.getInstance().readValue(data, AppleDecryptData.class);
return decryptDat;
} else {
return null;
}
}
private static final byte[] APPLE_OEM = "Apple".getBytes(Charset.forName("US-ASCII"));
private static final byte[] COUNTER = { 0x00, 0x00, 0x00, 0x01 };
private static final byte[] ALG_IDENTIFIER_BYTES = "id-aes256-GCM".getBytes(Charset.forName("US-ASCII"));
/**
* 00000001_16 || sharedSecret || length("AES/GCM/NoPadding") ||
* "AES/GCM/NoPadding" || "Apple" || merchantID
*/
private static byte[] performKDF(byte[] sharedSecret, byte[] merchantId) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(COUNTER);
baos.write(sharedSecret);
baos.write(ALG_IDENTIFIER_BYTES.length);
baos.write(ALG_IDENTIFIER_BYTES);
baos.write(APPLE_OEM);
baos.write(merchantId);
MessageDigest messageDigest = MessageDigest.getInstance("SHA256", PROVIDER_NAME);
return messageDigest.digest(baos.toByteArray());
}
#SuppressWarnings("unused")
private static byte[] performKDF(byte[] sharedSecret, String merchantId) throws Exception {
MessageDigest messageDigest = MessageDigest.getInstance("SHA256", PROVIDER_NAME);
return performKDF(sharedSecret, messageDigest.digest(merchantId.getBytes("UTF-8")));
}
protected static byte[] extractMerchantIdFromCertificateOid() throws Exception {
KeyStore vkeyStore = KeyStore.getInstance("JKS");
vkeyStore.load(GoSecureApplication.class.getResourceAsStream("/kapple_pay.jks"), "".toCharArray());
Enumeration<String> aliases = vkeyStore.aliases();
String alias = null;
while (aliases.hasMoreElements()) {
alias = aliases.nextElement();
}
X509Certificate cert = (X509Certificate) vkeyStore.getCertificate(alias);
byte[] merchantIdentifierTlv = cert.getExtensionValue("1.2.840.113635.100.6.32");
byte[] merchantIdentifier = new byte[64];
System.arraycopy(merchantIdentifierTlv, 4, merchantIdentifier, 0, 64);
return Hex.decode(merchantIdentifier);
}
}

Signing PDF with PDFBox and BouncyCastle

I'm trying to sign a PDF using PDFBox, and it does sign but when I open the document in adobe reader I get the following message "Document has been altered or corrupted since it was signed" can someone please help me find the problem.
The keystore was created with "keytool -genkeypair -storepass 123456 -storetype pkcs12 -alias test -validity 365 -v -keyalg RSA -keystore keystore.p12"
Using pdfbox-1.8.9 and bcpkix-jdk15on-1.52
Here is my code:
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.exceptions.SignatureException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureInterface;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.Store;
import java.io.*;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.Calendar;
import java.util.Collections;
import java.util.Enumeration;
public class CreateSignature implements SignatureInterface {
private static PrivateKey privateKey;
private static Certificate certificate;
boolean signPdf(File pdfFile, File signedPdfFile) {
try (
FileInputStream fis1 = new FileInputStream(pdfFile);
FileInputStream fis = new FileInputStream(pdfFile);
FileOutputStream fos = new FileOutputStream(signedPdfFile);
PDDocument doc = PDDocument.load(pdfFile)) {
int readCount;
byte[] buffer = new byte[8 * 1024];
while ((readCount = fis1.read(buffer)) != -1) {
fos.write(buffer, 0, readCount);
}
PDSignature signature = new PDSignature();
signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
signature.setName("NAME");
signature.setLocation("LOCATION");
signature.setReason("REASON");
signature.setSignDate(Calendar.getInstance());
doc.addSignature(signature, this);
doc.saveIncremental(fis, fos);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public byte[] sign(InputStream is) throws SignatureException, IOException {
try {
BouncyCastleProvider BC = new BouncyCastleProvider();
Store certStore = new JcaCertStore(Collections.singletonList(certificate));
CMSTypedDataInputStream input = new CMSTypedDataInputStream(is);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
ContentSigner sha512Signer = new JcaContentSignerBuilder("SHA256WithRSA").setProvider(BC).build(privateKey);
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha512Signer, new X509CertificateHolder(certificate.getEncoded())
));
gen.addCertificates(certStore);
CMSSignedData signedData = gen.generate(input, false);
return signedData.getEncoded();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) throws IOException, GeneralSecurityException, SignatureException, COSVisitorException {
char[] password = "123456".toCharArray();
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(new FileInputStream("/home/user/Desktop/keystore.p12"), password);
Enumeration<String> aliases = keystore.aliases();
String alias;
if (aliases.hasMoreElements()) {
alias = aliases.nextElement();
} else {
throw new KeyStoreException("Keystore is empty");
}
privateKey = (PrivateKey) keystore.getKey(alias, password);
Certificate[] certificateChain = keystore.getCertificateChain(alias);
certificate = certificateChain[0];
File inFile = new File("/home/user/Desktop/sign.pdf");
File outFile = new File("/home/user/Desktop/sign_signed.pdf");
new CreateSignature().signPdf(inFile, outFile);
}
}
class CMSTypedDataInputStream implements CMSTypedData {
InputStream in;
public CMSTypedDataInputStream(InputStream is) {
in = is;
}
#Override
public ASN1ObjectIdentifier getContentType() {
return PKCSObjectIdentifiers.data;
}
#Override
public Object getContent() {
return in;
}
#Override
public void write(OutputStream out) throws IOException,
CMSException {
byte[] buffer = new byte[8 * 1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
}
}
Fixing "Document has been altered or corrupted"
The mistake is that you call PDDocument.saveIncremental with an InputStream merely covering the original PDF:
FileInputStream fis1 = new FileInputStream(pdfFile);
FileInputStream fis = new FileInputStream(pdfFile);
FileOutputStream fos = new FileOutputStream(signedPdfFile);
...
doc.saveIncremental(fis, fos);
But the method expects the InputStream to cover the original file plus the changes made to prepare for signing.
Thus, fis also needs to point to signedPdfFile, and as that file might not exist before, the order of creating fis and fos must be switched>
FileInputStream fis1 = new FileInputStream(pdfFile);
FileOutputStream fos = new FileOutputStream(signedPdfFile);
FileInputStream fis = new FileInputStream(signedPdfFile);
...
doc.saveIncremental(fis, fos);
Unfortunately the JavaDocs don't Point this out.
Another issue
There is another issue with the generated signature. If you look at the ASN.1 dump of a sample result, you'll see something starting like this:
<30 80>
0 NDEF: SEQUENCE {
<06 09>
2 9: OBJECT IDENTIFIER signedData (1 2 840 113549 1 7 2)
: (PKCS #7)
<A0 80>
13 NDEF: [0] {
<30 80>
15 NDEF: SEQUENCE {
<02 01>
17 1: INTEGER 1
<31 0F>
20 15: SET {
The NDEF length indications show that the indefinite-length method is used for encoding these outer layers of the signature container. Use of this method is allowed in the Basic Encoding Rules (BER) but not in the more strict Distinguished Encoding Rules (DER). While using BER for the outer layers is allowed for generic PKCS#7/CMS signatures, the PDF specification clearly requires:
When PKCS#7 signatures are used, the value of Contents shall be a DER-encoded PKCS#7 binary data object containing the signature.
(section 12.8.3.3.1 "PKCS#7 Signatures as used in ISO 32000" / "General" in ISO 32000-1)
Thus, strictly speaking your signature is even structurally invalid. Usually, though, this is not detected by PDF signature verification services because most of them use standard PKCS#7/CMS libraries or methods for verifying the signature containers.
If you want to make sure that your signatures are truly valid PDF signatures, you can achieve this by replacing
return signedData.getEncoded();
by something like
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DEROutputStream dos = new DEROutputStream(baos);
dos.writeObject(signedData.toASN1Structure());
return baos.toByteArray();
Now the whole signature object is DER-encoded.
(You can find a test creating signatures both with your original and the fixed code either with or without improved encoding here: SignLikeLoneWolf.java)

org.bouncycastle.asn1.DLSequence cannot be cast to org.bouncycastle.asn1.ASN1Integer

I am trying to use BouncyCastle classes to encrypt and decrypt a password. I have written a test program and generated a test key/cert in PEM format as well as DER format. I can read the key/cert into my program and get the public key and encrypt a value. When I try to setup to decrypt the value I am getting the error "org.bouncycastle.asn1.DLSequence cannot be cast to org.bouncycastle.asn1.ASN1Integer" when creating the AsymmetricKeyParameter. It seems that when I am trying to pull in the data from the cert by doing the cert.getEncoded() it pulls in the header values as well. I tried just reading the file and removing the BEGIN and END CERTIFCATE lines, along with the dashes and that netted me the same error. I have tried used the java.security.cert.Certificate as well as the X509Certificate the code below is using. Any help would be greatly appreciated.
I can upload the key file is that would be helpful to you as it is a test key that I generated on my local machine and will be thrown away once I have this working.
package com.cds.test;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.Security;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
public class RSAEncryptDecrypt {
public X509Certificate cert = null;
//
public void readCertificate() throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
CertificateFactory factory = CertificateFactory.getInstance("X.509", new BouncyCastleProvider());
InputStream fis = new FileInputStream("/opt/temp/keys/openssl_crt.pem");
X509Certificate x509Cert = (X509Certificate) factory.generateCertificate(fis);
this.cert = x509Cert;
System.out.println("issuer: " + x509Cert.getIssuerX500Principal());
}
//
public String encrypt(String inputData) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//
System.out.println("public key: " + new String(Base64.encode(cert.getPublicKey().getEncoded())));
AsymmetricKeyParameter publicKey = PublicKeyFactory.createKey(cert.getPublicKey().getEncoded());
AsymmetricBlockCipher cipher = new RSAEngine();
cipher = new org.bouncycastle.crypto.encodings.PKCS1Encoding(cipher);
cipher.init(true, publicKey);
//
byte[] messageBytes = inputData.getBytes();
byte[] hexEncodedCipher = cipher.processBlock(messageBytes, 0, messageBytes.length);
//
return new String(Base64.encode(hexEncodedCipher));
}
//
private String decrypt (String encryptedData) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//
byte[] certData = cert.getEncoded();
//certData = Base64.decode(certData);
AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(cert.getEncoded());
AsymmetricBlockCipher cipher = new RSAEngine();
cipher = new org.bouncycastle.crypto.encodings.PKCS1Encoding(cipher);
cipher.init(false, privateKey);
//
byte[] decoded = Base64.decode(encryptedData.getBytes());
byte[] result = cipher.processBlock(decoded, 0, decoded.length);
//
return new String(result);
}
//
public static void main(String[] args) throws Exception {
String inputData = "This is the message I am trying to encrypt.";
String encrypted = null;
String decrypted = null;
//
RSAEncryptDecrypt rsa = new RSAEncryptDecrypt();
//
rsa.readCertificate();
System.out.println(" input: " + inputData);
encrypted = rsa.encrypt(inputData);
System.out.println("encrypted: " + encrypted);
decrypted = rsa.decrypt(encrypted);
System.out.println("decrypted: " + decrypted);
}
}
A certificate only contains the public key, not a private key. Of course the public key has a private key associated to it, but that is not kept in the certificate. The certificate is what you distribute to other parties.
It could be that you have been working with Microsoft code too much. I'm mentioning Microsoft as in .NET code the certificate class can internally contain the associated private key, making for a rather oversimplified API.
So to decrypt you will have to read the private key separately of your certificate (using PKCS8EncodedKeySpec and an "RSA" KeyFactory).
Another option is to put both in a PKCS#12 key store and read it into Java using KeyStore.load.

Encryption using PKCS#7

I am using Bouncy Castle provided library to encrypt,decrypt,sign and verify sign.
I am doing this as
1. Encrypt data
2. Sign data
3. Write signed byte to a file
4. Read signed byte from file
5. Verify signature
6. Decrypt data
I have taken reference from Beginning Cryptography with Java
My problem is in step 5 when i am verifying data i am getting
org.bouncycastle.cms.CMSException: message-digest attribute value does
not match calculated value
My code is below
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.CertPathBuilder;
import java.security.cert.CertStore;
import java.security.cert.Certificate;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.PKIXBuilderParameters;
import java.security.cert.PKIXCertPathBuilderResult;
import java.security.cert.TrustAnchor;
import java.security.cert.X509CertSelector;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import javax.security.auth.x500.X500Principal;
import javax.security.auth.x500.X500PrivateCredential;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.cms.CMSEnvelopedData;
import org.bouncycastle.cms.CMSEnvelopedDataGenerator;
import org.bouncycastle.cms.CMSEnvelopedDataParser;
import org.bouncycastle.cms.CMSProcessable;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.RecipientId;
import org.bouncycastle.cms.RecipientInformation;
import org.bouncycastle.cms.RecipientInformationStore;
import org.bouncycastle.cms.SignerId;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.x509.X509V1CertificateGenerator;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure;
import org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure;
public class Test {
private static final char[] KEY_STORE_PASSWORD = "123456".toCharArray();
private static final long VALIDITY_PERIOD = 365 * 24 * 60 * 60 * 1000;
private static final char[] KEY_PASSWORD = "keyPassword".toCharArray();
public static String ROOT_ALIAS = "root";
public static String INTERMEDIATE_ALIAS = "intermediate";
public static String END_ENTITY_ALIAS = "end";
public static String PLAIN_TEXT = "Hello World!123";
public static void main(String[] args) {
try{
// CREATE KEY STORE
KeyStore keyStore = createKeyStore();
// STEP 1. ENCRYPT AND SIGN
byte[] step1Data = encryptData(keyStore, PLAIN_TEXT.getBytes());
CMSSignedData cmsSignedData = signData(keyStore,step1Data);
new File("D:\\pkcs7\\encrypted-file.p7b");
FileOutputStream fileOuputStream = new FileOutputStream("D:\\pkcs7\\encrypted-file.p7b");
fileOuputStream.write(cmsSignedData.getEncoded());
fileOuputStream.flush();
fileOuputStream.close();
// STEP 2. READ ENCRYPTED DATA AND VERIFY SIGN AND DECRYPT IT
File file =new File("D:\\pkcs7\\encrypted-file.p7b");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] encryptedAndSignedByte = new byte[(int)file.length()];
fileInputStream.read(encryptedAndSignedByte );
fileInputStream.close();
cmsSignedData = new CMSSignedData(encryptedAndSignedByte);
if( verifyData(keyStore, cmsSignedData) == true ){
decryptData(keyStore,encryptedAndSignedByte);
}
}catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* This method will encrypt data
*/
private static byte[] encryptData(KeyStore keyStore, byte[] plainData) throws Exception {
PrivateKey key = (PrivateKey) keyStore.getKey(END_ENTITY_ALIAS,
KEY_PASSWORD);
Certificate[] chain = keyStore.getCertificateChain(END_ENTITY_ALIAS);
X509Certificate cert = (X509Certificate) chain[0];
// set up the generator
CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();
gen.addKeyTransRecipient(cert);
// create the enveloped-data object
CMSProcessable data = new CMSProcessableByteArray(plainData);
CMSEnvelopedData enveloped = gen.generate(data,
CMSEnvelopedDataGenerator.AES128_CBC, "BC");
return enveloped.getEncoded();
// recreate
}
private static byte[] decryptData(KeyStore keyStore,byte[] encryptedData) throws Exception{
CMSEnvelopedDataParser envelopedDataParser = new CMSEnvelopedDataParser(new ByteArrayInputStream(encryptedData));
PrivateKey key = (PrivateKey) keyStore.getKey(END_ENTITY_ALIAS,KEY_PASSWORD);
Certificate[] chain = keyStore.getCertificateChain(END_ENTITY_ALIAS);
X509Certificate cert = (X509Certificate) chain[0];
CMSEnvelopedData enveloped = new CMSEnvelopedData(encryptedData);
// look for our recipient identifier
RecipientId recId = new RecipientId();
recId.setSerialNumber(cert.getSerialNumber());
recId.setIssuer(cert.getIssuerX500Principal().getEncoded());
RecipientInformationStore recipients = enveloped.getRecipientInfos();
RecipientInformation recipient = recipients.get(recId);
if (recipient != null) {
// decrypt the data
byte[] recData = recipient.getContent(key, "BC");
System.out.println("----------------------- RECOVERED DATA -----------------------");
System.out.println(new String(recData));
System.out.println("--------------------------------------------------------------");
return recData;
} else {
System.out.println("could not find a matching recipient");
}
return null;
}
private static CMSSignedData signData(KeyStore keyStore,byte[] encryptedData ) throws Exception {
// GET THE PRIVATE KEY
PrivateKey key = (PrivateKey) keyStore.getKey(END_ENTITY_ALIAS,
KEY_PASSWORD);
Certificate[] chain = keyStore.getCertificateChain(END_ENTITY_ALIAS);
CertStore certsAndCRLs = CertStore.getInstance("Collection",
new CollectionCertStoreParameters(Arrays.asList(chain)), "BC");
X509Certificate cert = (X509Certificate) chain[0];
// set up the generator
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
gen.addSigner(key, cert, CMSSignedDataGenerator.DIGEST_SHA224);
gen.addCertificatesAndCRLs(certsAndCRLs);
// create the signed-data object
CMSProcessable data = new CMSProcessableByteArray(encryptedData);
CMSSignedData signed = gen.generate(data, "BC");
// recreate
signed = new CMSSignedData(data, signed.getEncoded());
// ContentInfo conInf = signed.getContentInfo();
// CMSProcessable sigContent = signed.getSignedContent();
return signed;
}
private static boolean verifyData(KeyStore keyStore, CMSSignedData signed)
throws Exception {
// verification step
X509Certificate rootCert = (X509Certificate) keyStore.getCertificate(ROOT_ALIAS);
if (isValidSignature(signed, rootCert)) {
System.out.println("verification succeeded");
return true;
} else {
System.out.println("verification failed");
}
return false;
}
/**
* Take a CMS SignedData message and a trust anchor and determine if the
* message is signed with a valid signature from a end entity entity
* certificate recognized by the trust anchor rootCert.
*/
private static boolean isValidSignature(CMSSignedData signedData,
X509Certificate rootCert) throws Exception {
boolean[] bArr = new boolean[2];
bArr[0] = true;
CertStore certsAndCRLs = signedData.getCertificatesAndCRLs(
"Collection", "BC");
SignerInformationStore signers = signedData.getSignerInfos();
Iterator it = signers.getSigners().iterator();
if (it.hasNext()) {
SignerInformation signer = (SignerInformation) it.next();
SignerId signerConstraints = signer.getSID();
signerConstraints.setKeyUsage(bArr);
PKIXCertPathBuilderResult result = buildPath(rootCert,
signer.getSID(), certsAndCRLs);
return signer.verify(result.getPublicKey(), "BC");
}
return false;
}
/**
* Build a path using the given root as the trust anchor, and the passed in
* end constraints and certificate store.
* <p>
* Note: the path is built with revocation checking turned off.
*/
public static PKIXCertPathBuilderResult buildPath(X509Certificate rootCert,
X509CertSelector endConstraints, CertStore certsAndCRLs)
throws Exception {
CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
PKIXBuilderParameters buildParams = new PKIXBuilderParameters(
Collections.singleton(new TrustAnchor(rootCert, null)),
endConstraints);
buildParams.addCertStore(certsAndCRLs);
buildParams.setRevocationEnabled(false);
return (PKIXCertPathBuilderResult) builder.build(buildParams);
}
/**
* Create a KeyStore containing the a private credential with certificate
* chain and a trust anchor.
*/
public static KeyStore createKeyStore() throws Exception {
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
keyStore.load(null, null);
X500PrivateCredential rootCredential = createRootCredential();
X500PrivateCredential interCredential = createIntermediateCredential(
rootCredential.getPrivateKey(), rootCredential.getCertificate());
X500PrivateCredential endCredential = createEndEntityCredential(
interCredential.getPrivateKey(),
interCredential.getCertificate());
keyStore.setCertificateEntry(rootCredential.getAlias(),
rootCredential.getCertificate());
keyStore.setKeyEntry(
endCredential.getAlias(),
endCredential.getPrivateKey(),
KEY_PASSWORD,
new Certificate[] { endCredential.getCertificate(),
interCredential.getCertificate(),
rootCredential.getCertificate() });
keyStore.store(new FileOutputStream("d:\\pkcs7\\KeyStore.jks"),
KEY_STORE_PASSWORD);
return keyStore;
}
/**
* Create a random 1024 bit RSA key pair
*/
public static KeyPair generateRSAKeyPair() throws Exception {
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
kpGen.initialize(1024, new SecureRandom());
return kpGen.generateKeyPair();
}
/**
* Generate a sample V1 certificate to use as a CA root certificate
*/
public static X509Certificate generateCertificate(KeyPair pair)
throws Exception {
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X500Principal("CN=Test CA Certificate"));
certGen.setNotBefore(new Date(System.currentTimeMillis()
- VALIDITY_PERIOD));
certGen.setNotAfter(new Date(System.currentTimeMillis()
+ VALIDITY_PERIOD));
certGen.setSubjectDN(new X500Principal("CN=Test CA Certificate"));
certGen.setPublicKey(pair.getPublic());
certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}
/**
* Generate a sample V1 certificate to use as a CA root certificate
*/
public static X509Certificate generateRootCert(KeyPair pair)
throws Exception {
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X500Principal("CN=Test CA Certificate"));
certGen.setNotBefore(new Date(System.currentTimeMillis()
- VALIDITY_PERIOD));
certGen.setNotAfter(new Date(System.currentTimeMillis()
+ VALIDITY_PERIOD));
certGen.setSubjectDN(new X500Principal("CN=Test CA Certificate"));
certGen.setPublicKey(pair.getPublic());
certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}
/**
* Generate a sample V3 certificate to use as an end entity certificate
*/
public static X509Certificate generateEndEntityCert(PublicKey entityKey,
PrivateKey caKey, X509Certificate caCert) throws Exception {
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(caCert.getSubjectX500Principal());
certGen.setNotBefore(new Date(System.currentTimeMillis()
- VALIDITY_PERIOD));
certGen.setNotAfter(new Date(System.currentTimeMillis()
+ VALIDITY_PERIOD));
certGen.setSubjectDN(new X500Principal("CN=Test End Certificate"));
certGen.setPublicKey(entityKey);
certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
new AuthorityKeyIdentifierStructure(caCert));
certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
new SubjectKeyIdentifierStructure(entityKey));
certGen.addExtension(X509Extensions.BasicConstraints, true,
new BasicConstraints(false));
certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(
KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
return certGen.generateX509Certificate(caKey, "BC");
}
/**
* Generate a X500PrivateCredential for the root entity.
*/
public static X500PrivateCredential createRootCredential() throws Exception {
KeyPair rootPair = generateRSAKeyPair();
X509Certificate rootCert = generateRootCert(rootPair);
return new X500PrivateCredential(rootCert, rootPair.getPrivate(),
ROOT_ALIAS);
}
/**
* Generate a X500PrivateCredential for the intermediate entity.
*/
public static X500PrivateCredential createIntermediateCredential(
PrivateKey caKey, X509Certificate caCert) throws Exception {
KeyPair interPair = generateRSAKeyPair();
X509Certificate interCert = generateIntermediateCert(
interPair.getPublic(), caKey, caCert);
return new X500PrivateCredential(interCert, interPair.getPrivate(),
INTERMEDIATE_ALIAS);
}
/**
* Generate a X500PrivateCredential for the end entity.
*/
public static X500PrivateCredential createEndEntityCredential(
PrivateKey caKey, X509Certificate caCert) throws Exception {
KeyPair endPair = generateRSAKeyPair();
X509Certificate endCert = generateEndEntityCert(endPair.getPublic(),
caKey, caCert);
return new X500PrivateCredential(endCert, endPair.getPrivate(),
END_ENTITY_ALIAS);
}
/**
* Generate a sample V3 certificate to use as an intermediate CA certificate
*/
public static X509Certificate generateIntermediateCert(PublicKey intKey,
PrivateKey caKey, X509Certificate caCert) throws Exception {
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(caCert.getSubjectX500Principal());
certGen.setNotBefore(new Date(System.currentTimeMillis()));
certGen.setNotAfter(new Date(System.currentTimeMillis()
+ VALIDITY_PERIOD));
certGen.setSubjectDN(new X500Principal(
"CN=Test Intermediate Certificate"));
certGen.setPublicKey(intKey);
certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
new AuthorityKeyIdentifierStructure(caCert));
certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
new SubjectKeyIdentifierStructure(intKey));
certGen.addExtension(X509Extensions.BasicConstraints, true,
new BasicConstraints(0));
certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(
KeyUsage.digitalSignature | KeyUsage.keyCertSign
| KeyUsage.cRLSign));
return certGen.generateX509Certificate(caKey, "BC");
}
}
In typical usage a .p7b file contains only public key certificates and never a private key. It is often used to store an entire chain of certificates rather than a single certificate. The 'p7b' name comes from the format which is the degenerate form of PKCS#7 SignedData structure. Typically, private keys are stored in a PKCS#12 (often a file that has either a .p12 or a .pfx extension) file but other formats are also common.
To read in the certificates from a p7b file you can use the CertificateFactory class. A PKCS#12 file is directly usable as a keystore.
You mention PKCS#7 frequently. PKCS#7 is an old standard that is extremely large and open ended. These days the standard that is more commonly implemented is an extended subset of PKCS#7 called CMS. It's an IETF standard documented in RFC 5652. The Bouncycastle PKIX/CMS library has extensive support for the CMS specification.
try {
File file = new File("d:\\TESTS\\VG.p7b");
FileInputStream fis = new FileInputStream(file);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Collection c = cf.generateCertificates(fis);
Iterator i = c.iterator();
while (i.hasNext()) {
X509Certificate cert509 = (X509Certificate) i.next();
System.out.println(cert509);
}
}
catch (Throwable th) {
th.printStackTrace();
}

Categories

Resources