use of org.bouncycastle.cms.CMSEnvelopedData in project xipki by xipki.
the class PkiMessage method encode.
public ContentInfo encode(ContentSigner signer, X509Certificate signerCert, X509Certificate[] cmsCertSet, X509Certificate recipientCert, ASN1ObjectIdentifier encAlgId) throws MessageEncodingException {
ScepUtil.requireNonNull("signer", signer);
ScepUtil.requireNonNull("signerCert", signerCert);
if (messageData != null) {
ScepUtil.requireNonNull("recipientCert", recipientCert);
ScepUtil.requireNonNull("encAlgId", encAlgId);
}
CMSTypedData content;
if (messageData == null) {
content = new CMSAbsentContent();
} else {
CMSEnvelopedData envelopedData = encrypt(recipientCert, encAlgId);
byte[] encoded;
try {
encoded = envelopedData.getEncoded();
} catch (IOException ex) {
throw new MessageEncodingException(ex);
}
content = new CMSProcessableByteArray(CMSObjectIdentifiers.envelopedData, encoded);
}
try {
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
// signerInfo
JcaSignerInfoGeneratorBuilder signerInfoBuilder = new JcaSignerInfoGeneratorBuilder(new BcDigestCalculatorProvider());
signerInfoBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(getSignedAttributes()));
AttributeTable attrTable = getUnsignedAttributes();
if (attrTable != null) {
signerInfoBuilder.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(attrTable));
}
// certificateSet
ScepUtil.addCmsCertSet(generator, cmsCertSet);
SignerInfoGenerator signerInfo;
try {
signerInfo = signerInfoBuilder.build(signer, signerCert);
} catch (Exception ex) {
throw new MessageEncodingException(ex);
}
generator.addSignerInfoGenerator(signerInfo);
CMSSignedData signedData = generator.generate(content, true);
return signedData.toASN1Structure();
} catch (CMSException ex) {
throw new MessageEncodingException(ex);
} catch (Exception ex) {
throw new MessageEncodingException(ex);
}
}
use of org.bouncycastle.cms.CMSEnvelopedData in project serverless by bluenimble.
the class EncryptDocument method main.
public static void main(String[] args) throws IOException, CertificateException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException, CertStoreException, CMSException, NoSuchPaddingException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException {
File f = new File("ToBeEncrypted.txt");
byte[] buffer = new byte[(int) f.length()];
DataInputStream in = new DataInputStream(new FileInputStream(f));
in.readFully(buffer);
in.close();
// Chiffrement du document
// La variable cert correspond au certificat du destinataire
// La cl� publique de ce certificat servira � chiffrer la cl� sym�trique
X509Certificate cert = ReadX509.read(new FileInputStream("files/test.cer"));
CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();
RecipientInfoGenerator recipientGenerator = new JceKeyTransRecipientInfoGenerator(cert).setProvider("BC");
gen.addRecipientInfoGenerator(recipientGenerator);
// Choix de l'algorithme � cl� sym�trique pour chiffrer le document.
// AES est un standard. Vous pouvez donc l'utiliser sans crainte.
// Il faut savoir qu'en france la taille maximum autoris�e est de 128 bits pour les cl�s sym�triques (ou cl�s secr�tes)
OutputEncryptor outputEncryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).build();
CMSEnvelopedData envData = gen.generate(new CMSProcessableByteArray(buffer), outputEncryptor);
byte[] pkcs7envelopedData = envData.getEncoded();
// Ecriture du document chiffr�
FileOutputStream envfos = new FileOutputStream("ToBeDecrypted.pk7");
envfos.write(pkcs7envelopedData);
envfos.close();
}
use of org.bouncycastle.cms.CMSEnvelopedData in project ddf by codice.
the class KeystoreEditor method addToStore.
private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data, String type, String fileName, String path, String storepass, KeyStore store) throws KeystoreEditorException {
OutputStream fos = null;
try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
if (StringUtils.isBlank(alias)) {
throw new IllegalArgumentException(NULL_ALIAS_MSG);
}
Path storeFile = Paths.get(path);
// check the two most common key/cert stores first (pkcs12 and jks)
if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
// priv key + cert chain
KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
pkcs12Store.load(inputStream, storePassword.toCharArray());
Certificate[] chain = pkcs12Store.getCertificateChain(alias);
Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
if (key != null) {
store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
fos = Files.newOutputStream(storeFile);
store.store(fos, storepass.toCharArray());
}
} else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
// java keystore file
KeyStore jks = KeyStore.getInstance("jks");
jks.load(inputStream, storePassword.toCharArray());
Enumeration<String> aliases = jks.aliases();
// we are going to store all entries from the jks regardless of the passed in alias
while (aliases.hasMoreElements()) {
String jksAlias = aliases.nextElement();
if (jks.isKeyEntry(jksAlias)) {
Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
} else {
Certificate certificate = jks.getCertificate(jksAlias);
store.setCertificateEntry(jksAlias, certificate);
}
}
fos = Files.newOutputStream(storeFile);
store.store(fos, storepass.toCharArray());
// need to parse der separately from pem, der has the same mime type but is binary hence
// checking both
} else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
ASN1Primitive asn1Primitive = asn1InputStream.readObject();
X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
CertificateFactory certificateFactory = CertificateFactory.getInstance(X509, "BC");
Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
RDN cn = x500name.getRDNs(BCStyle.CN)[0];
String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
store.setCertificateEntry(cnStr, certificate);
}
store.setCertificateEntry(alias, certificate);
fos = Files.newOutputStream(storeFile);
store.store(fos, storepass.toCharArray());
// if it isn't one of the stores we support, it might be a key or cert by itself
} else if (isPemParsable(type, fileName)) {
// This is the catch all case for PEM, P7B, etc. with common file extensions if the mime
// type isn't read correctly in the browser
Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
PEMParser pemParser = new PEMParser(reader);
Object object;
boolean setEntry = false;
while ((object = pemParser.readObject()) != null) {
if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
PEMKeyPair pemKeyPair;
if (object instanceof PEMEncryptedKeyPair) {
PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
} else {
pemKeyPair = (PEMKeyPair) object;
}
KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
PrivateKey privateKey = keyPair.getPrivate();
Certificate[] chain = store.getCertificateChain(alias);
if (chain == null) {
chain = buildCertChain(alias, store);
}
store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
setEntry = true;
} else if (object instanceof X509CertificateHolder) {
X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
CertificateFactory certificateFactory = CertificateFactory.getInstance(X509, "BC");
Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
RDN cn = x500name.getRDNs(BCStyle.CN)[0];
String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
store.setCertificateEntry(cnStr, certificate);
}
store.setCertificateEntry(alias, certificate);
setEntry = true;
} else if (object instanceof ContentInfo) {
ContentInfo contentInfo = (ContentInfo) object;
if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
ASN1Set certificates = originatorInfo.getCertificates();
setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
} else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
SignedData signedData = SignedData.getInstance(contentInfo.getContent());
ASN1Set certificates = signedData.getCertificates();
setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
}
} else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
Certificate[] chain = store.getCertificateChain(alias);
if (chain == null) {
chain = buildCertChain(alias, store);
}
try {
store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
setEntry = true;
} catch (KeyStoreException keyEx) {
try {
PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(), keyPassword.toCharArray());
store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(), chain);
setEntry = true;
} catch (GeneralSecurityException e) {
LOGGER.info("Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.", e);
throw keyEx;
}
}
}
}
if (setEntry) {
fos = Files.newOutputStream(storeFile);
store.store(fos, storepass.toCharArray());
}
}
} catch (Exception e) {
LOGGER.info("Unable to add entry {} to store", alias, e);
throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ignore) {
}
}
}
init();
}
use of org.bouncycastle.cms.CMSEnvelopedData in project xipki by xipki.
the class DecodedPkiMessage method decode.
@SuppressWarnings("unchecked")
public static DecodedPkiMessage decode(CMSSignedData pkiMessage, EnvelopedDataDecryptor recipient, CollectionStore<X509CertificateHolder> certStore) throws MessageDecodingException {
ScepUtil.requireNonNull("pkiMessage", pkiMessage);
ScepUtil.requireNonNull("recipient", recipient);
SignerInformationStore signerStore = pkiMessage.getSignerInfos();
Collection<SignerInformation> signerInfos = signerStore.getSigners();
if (signerInfos.size() != 1) {
throw new MessageDecodingException("number of signerInfos is not 1, but " + signerInfos.size());
}
SignerInformation signerInfo = signerInfos.iterator().next();
SignerId sid = signerInfo.getSID();
Collection<?> signedDataCerts = null;
if (certStore != null) {
signedDataCerts = certStore.getMatches(sid);
}
if (signedDataCerts == null || signedDataCerts.isEmpty()) {
signedDataCerts = pkiMessage.getCertificates().getMatches(signerInfo.getSID());
}
if (signedDataCerts == null || signedDataCerts.size() != 1) {
throw new MessageDecodingException("could not find embedded certificate to verify the signature");
}
AttributeTable signedAttrs = signerInfo.getSignedAttributes();
if (signedAttrs == null) {
throw new MessageDecodingException("missing SCEP attributes");
}
Date signingTime = null;
// signingTime
ASN1Encodable attrValue = ScepUtil.getFirstAttrValue(signedAttrs, CMSAttributes.signingTime);
if (attrValue != null) {
signingTime = Time.getInstance(attrValue).getDate();
}
// transactionId
String str = getPrintableStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_TRANSACTION_ID);
if (str == null || str.isEmpty()) {
throw new MessageDecodingException("missing required SCEP attribute transactionId");
}
TransactionId transactionId = new TransactionId(str);
// messageType
Integer intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_MESSAGE_TYPE);
if (intValue == null) {
throw new MessageDecodingException("tid " + transactionId.getId() + ": missing required SCEP attribute messageType");
}
MessageType messageType;
try {
messageType = MessageType.forValue(intValue);
} catch (IllegalArgumentException ex) {
throw new MessageDecodingException("tid " + transactionId.getId() + ": invalid messageType '" + intValue + "'");
}
// senderNonce
Nonce senderNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_SENDER_NONCE);
if (senderNonce == null) {
throw new MessageDecodingException("tid " + transactionId.getId() + ": missing required SCEP attribute senderNonce");
}
DecodedPkiMessage ret = new DecodedPkiMessage(transactionId, messageType, senderNonce);
if (signingTime != null) {
ret.setSigningTime(signingTime);
}
Nonce recipientNonce = null;
try {
recipientNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_RECIPIENT_NONCE);
} catch (MessageDecodingException ex) {
ret.setFailureMessage("could not parse recipientNonce: " + ex.getMessage());
}
if (recipientNonce != null) {
ret.setRecipientNonce(recipientNonce);
}
PkiStatus pkiStatus = null;
FailInfo failInfo = null;
if (MessageType.CertRep == messageType) {
// pkiStatus
try {
intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_PKI_STATUS);
} catch (MessageDecodingException ex) {
ret.setFailureMessage("could not parse pkiStatus: " + ex.getMessage());
return ret;
}
if (intValue == null) {
ret.setFailureMessage("missing required SCEP attribute pkiStatus");
return ret;
}
try {
pkiStatus = PkiStatus.forValue(intValue);
} catch (IllegalArgumentException ex) {
ret.setFailureMessage("invalid pkiStatus '" + intValue + "'");
return ret;
}
ret.setPkiStatus(pkiStatus);
// failureInfo
if (pkiStatus == PkiStatus.FAILURE) {
try {
intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_FAILINFO);
} catch (MessageDecodingException ex) {
ret.setFailureMessage("could not parse failInfo: " + ex.getMessage());
return ret;
}
if (intValue == null) {
ret.setFailureMessage("missing required SCEP attribute failInfo");
return ret;
}
try {
failInfo = FailInfo.forValue(intValue);
} catch (IllegalArgumentException ex) {
ret.setFailureMessage("invalid failInfo '" + intValue + "'");
return ret;
}
ret.setFailInfo(failInfo);
}
// end if(pkiStatus == PkiStatus.FAILURE)
}
// end if (MessageType.CertRep == messageType)
// other signedAttributes
Attribute[] attrs = signedAttrs.toASN1Structure().getAttributes();
for (Attribute attr : attrs) {
ASN1ObjectIdentifier type = attr.getAttrType();
if (!SCEP_ATTR_TYPES.contains(type)) {
ret.addSignendAttribute(type, attr.getAttrValues().getObjectAt(0));
}
}
// unsignedAttributes
AttributeTable unsignedAttrs = signerInfo.getUnsignedAttributes();
attrs = (unsignedAttrs == null) ? null : unsignedAttrs.toASN1Structure().getAttributes();
if (attrs != null) {
for (Attribute attr : attrs) {
ASN1ObjectIdentifier type = attr.getAttrType();
ret.addUnsignendAttribute(type, attr.getAttrValues().getObjectAt(0));
}
}
ASN1ObjectIdentifier digestAlgOid = signerInfo.getDigestAlgorithmID().getAlgorithm();
ret.setDigestAlgorithm(digestAlgOid);
String sigAlgOid = signerInfo.getEncryptionAlgOID();
if (!PKCSObjectIdentifiers.rsaEncryption.getId().equals(sigAlgOid)) {
ASN1ObjectIdentifier tmpDigestAlgOid;
try {
tmpDigestAlgOid = ScepUtil.extractDigesetAlgorithmIdentifier(signerInfo.getEncryptionAlgOID(), signerInfo.getEncryptionAlgParams());
} catch (Exception ex) {
final String msg = "could not extract digest algorithm from signerInfo.signatureAlgorithm: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
if (!digestAlgOid.equals(tmpDigestAlgOid)) {
ret.setFailureMessage("digestAlgorithm and encryptionAlgorithm do not use the same digestAlgorithm");
return ret;
}
// end if
}
// end if
X509CertificateHolder tmpSignerCert = (X509CertificateHolder) signedDataCerts.iterator().next();
X509Certificate signerCert;
try {
signerCert = ScepUtil.toX509Cert(tmpSignerCert.toASN1Structure());
} catch (CertificateException ex) {
final String msg = "could not construct X509Certificate: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
ret.setSignatureCert(signerCert);
// validate the signature
SignerInformationVerifier verifier;
try {
verifier = new JcaSimpleSignerInfoVerifierBuilder().build(tmpSignerCert);
} catch (OperatorCreationException | CertificateException ex) {
final String msg = "could not build signature verifier: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
boolean signatureValid;
try {
signatureValid = signerInfo.verify(verifier);
} catch (CMSException ex) {
final String msg = "could not verify the signature: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
ret.setSignatureValid(signatureValid);
if (!signatureValid) {
return ret;
}
if (MessageType.CertRep == messageType && (pkiStatus == PkiStatus.FAILURE | pkiStatus == PkiStatus.PENDING)) {
return ret;
}
// MessageData
CMSTypedData signedContent = pkiMessage.getSignedContent();
ASN1ObjectIdentifier signedContentType = signedContent.getContentType();
if (!CMSObjectIdentifiers.envelopedData.equals(signedContentType)) {
// fall back: some SCEP client, such as JSCEP use id-data
if (!CMSObjectIdentifiers.data.equals(signedContentType)) {
ret.setFailureMessage("either id-envelopedData or id-data is excepted, but not '" + signedContentType.getId());
return ret;
}
}
CMSEnvelopedData envData;
try {
envData = new CMSEnvelopedData((byte[]) signedContent.getContent());
} catch (CMSException ex) {
final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
ret.setContentEncryptionAlgorithm(envData.getContentEncryptionAlgorithm().getAlgorithm());
byte[] encodedMessageData;
try {
encodedMessageData = recipient.decrypt(envData);
} catch (MessageDecodingException ex) {
final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
ret.setDecryptionSuccessful(false);
return ret;
}
ret.setDecryptionSuccessful(true);
try {
if (MessageType.PKCSReq == messageType || MessageType.RenewalReq == messageType || MessageType.UpdateReq == messageType) {
CertificationRequest messageData = CertificationRequest.getInstance(encodedMessageData);
ret.setMessageData(messageData);
} else if (MessageType.CertPoll == messageType) {
IssuerAndSubject messageData = IssuerAndSubject.getInstance(encodedMessageData);
ret.setMessageData(messageData);
} else if (MessageType.GetCert == messageType || MessageType.GetCRL == messageType) {
IssuerAndSerialNumber messageData = IssuerAndSerialNumber.getInstance(encodedMessageData);
ret.setMessageData(messageData);
ret.setMessageData(messageData);
} else if (MessageType.CertRep == messageType) {
ContentInfo ci = ContentInfo.getInstance(encodedMessageData);
ret.setMessageData(ci);
} else {
throw new RuntimeException("should not reach here, unknown messageType " + messageType);
}
} catch (Exception ex) {
final String msg = "could not parse the messageData: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
return ret;
}
use of org.bouncycastle.cms.CMSEnvelopedData in project xipki by xipki.
the class PkiMessage method encrypt.
// method encode
private CMSEnvelopedData encrypt(X509Certificate recipient, ASN1ObjectIdentifier encAlgId) throws MessageEncodingException {
ScepUtil.requireNonNull("recipient", recipient);
ScepUtil.requireNonNull("encAlgId", encAlgId);
byte[] messageDataBytes;
try {
messageDataBytes = messageData.toASN1Primitive().getEncoded();
} catch (IOException ex) {
throw new MessageEncodingException(ex);
}
CMSEnvelopedDataGenerator edGenerator = new CMSEnvelopedDataGenerator();
CMSTypedData envelopable = new CMSProcessableByteArray(messageDataBytes);
RecipientInfoGenerator recipientGenerator;
try {
recipientGenerator = new JceKeyTransRecipientInfoGenerator(recipient);
} catch (CertificateEncodingException ex) {
throw new MessageEncodingException(ex);
}
edGenerator.addRecipientInfoGenerator(recipientGenerator);
try {
OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(encAlgId).build();
CMSEnvelopedData pkcsPkiEnvelope = edGenerator.generate(envelopable, encryptor);
return pkcsPkiEnvelope;
} catch (CMSException ex) {
throw new MessageEncodingException(ex);
}
}
Aggregations