List of usage examples for org.bouncycastle.cms SignerInformation getEncryptionAlgOID
public String getEncryptionAlgOID()
From source file:org.xipki.pki.scep.message.DecodedPkiMessage.java
License:Open Source License
@SuppressWarnings("unchecked") public static DecodedPkiMessage decode(final CMSSignedData pkiMessage, final EnvelopedDataDecryptor recipient, final CollectionStore<X509CertificateHolder> certStore) throws MessageDecodingException { ParamUtil.requireNonNull("pkiMessage", pkiMessage); ParamUtil.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()); }/*from ww w. j ava 2s . c om*/ 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(signerCert.getPublicKey()); } catch (OperatorCreationException 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; }
From source file:se.tillvaxtverket.ttsigvalws.ttwssigvalidation.pdf.PdfSignatureVerifier.java
License:Open Source License
private static void verifyCMSSignature(CMSSignedDataParser sp, CMSSigVerifyResult sigResult) throws CMSException, IOException, CertificateException, OperatorCreationException { CollectionStore certStore = (CollectionStore) sp.getCertificates(); Iterator ci = certStore.iterator(); List<X509Certificate> certList = new ArrayList<>(); while (ci.hasNext()) { X509CertificateHolder ch = (X509CertificateHolder) ci.next(); certList.add(getCert(ch));/*ww w . j ava 2s . c o m*/ } sigResult.setCertList(certList); SignerInformationStore signers = sp.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Date claimedSigningTime = getClaimedSigningTime(signer); sigResult.setClaimedSigningTime(claimedSigningTime); Collection certCollection = certStore.getMatches(signer.getSID()); X509CertificateHolder certHolder = (X509CertificateHolder) certCollection.iterator().next(); sigResult.setCert(getCert(certHolder)); //Check signature sigResult.setValid( signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certHolder))); sigResult.setStatus(sigResult.isValid() ? "Valid" : "Signature verification failed"); if (!sigResult.isValid()) { return; } // Collect sig algo data getPkParams(sigResult.getCert().getPublicKey(), sigResult); DigestAlgorithm signerInfoHashAlgo = DigestAlgorithm.getDigestAlgoFromOid(signer.getDigestAlgOID()); sigResult.setDigestAlgo(signerInfoHashAlgo); String encryptionAlgOID = signer.getEncryptionAlgOID(); SupportedSigAlgoritm sigAlgoFromSignerInfoAndCert = SupportedSigAlgoritm .getAlgoFromOidAndHash(new ASN1ObjectIdentifier(encryptionAlgOID), signerInfoHashAlgo); sigResult.setSigAlgo(sigAlgoFromSignerInfoAndCert); Attribute cmsAlgoProtAttr = signer.getSignedAttributes() .get(new ASN1ObjectIdentifier(PdfObjectIds.ID_AA_CMS_ALGORITHM_PROTECTION)); getCMSAlgoritmProtectionData(cmsAlgoProtAttr, sigResult); if (!checkAlgoritmConsistency(sigResult)) { sigResult.setValid(false); sigResult.setStatus( "Signature was verified but with inconsistent Algoritm declarations or unsupported algoritms"); } if (sigResult.isValid()) { verifyPadesProperties(signer, sigResult); } } }