List of usage examples for org.bouncycastle.asn1.cms ContentInfo ContentInfo
public ContentInfo(ASN1ObjectIdentifier contentType, ASN1Encodable content)
From source file:org.votingsystem.signature.dnie.DNIePDFContentSigner.java
License:Open Source License
public CMSSignedData getCMSSignedData(String eContentType, CMSProcessable content, boolean encapsulate, Provider sigProvider, boolean addDefaultAttributes, List signerInfs) throws Exception { // TODO if (signerInfs.isEmpty()){ // /* RFC 3852 5.2 // * "In the degenerate case where there are no signers, the // * EncapsulatedContentInfo value being "signed" is irrelevant. In this // * case, the content type within the EncapsulatedContentInfo value being // * "signed" MUST be id-data (as defined in section 4), and the content // * field of the EncapsulatedContentInfo value MUST be omitted." // *///from w w w . j a va 2s .c om // if (encapsulate) { // throw new IllegalArgumentException("no signers, encapsulate must be false"); // } if (!DATA.equals(eContentType)) { // throw new IllegalArgumentException("no signers, eContentType must be id-data"); // } // } // if (!DATA.equals(eContentType)) { // /* RFC 3852 5.3 // * [The 'signedAttrs']... // * field is optional, but it MUST be present if the content type of // * the EncapsulatedContentInfo value being signed is not id-data. // */ // // TODO signedAttrs must be present for all signers // } ASN1EncodableVector digestAlgs = new ASN1EncodableVector(); ASN1EncodableVector signerInfos = new ASN1EncodableVector(); digests.clear(); // clear the current preserved digest state Iterator it = _signers.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); digestAlgs.add(CMSUtils.fixAlgID(signer.getDigestAlgorithmID())); signerInfos.add(signer.toSignerInfo()); } boolean isCounterSignature = (eContentType == null); ASN1ObjectIdentifier contentTypeOID = isCounterSignature ? CMSObjectIdentifiers.data : new ASN1ObjectIdentifier(eContentType); it = signerInfs.iterator(); while (it.hasNext()) { SignerInf signer = (SignerInf) it.next(); log.info("signer.signerIdentifier: " + signer.signerIdentifier.toASN1Object().toString()); digestAlgs.add(signer.getDigestAlgorithmID()); signerInfos.add(signer.toSignerInfo(contentTypeOID, content, rand, null, addDefaultAttributes, isCounterSignature)); } ASN1Set certificates = null; if (!certs.isEmpty()) certificates = CMSUtils.createBerSetFromList(certs); ASN1Set certrevlist = null; if (!crls.isEmpty()) certrevlist = CMSUtils.createBerSetFromList(crls); ASN1OctetString octs = null; if (encapsulate && content != null) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); content.write(bOut); octs = new BERConstructedOctetString(bOut.toByteArray()); } ContentInfo encInfo = new ContentInfo(contentTypeOID, octs); SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist, new DERSet(signerInfos)); ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd); return new CMSSignedData(content, contentInfo); }
From source file:org.votingsystem.signature.util.PDFContentSigner.java
License:Open Source License
public CMSSignedData getCMSSignedData(String eContentType, CMSProcessable content, boolean encapsulate, Provider sigProvider, boolean addDefaultAttributes, List<SignerInfo> signerInfoList) throws NoSuchAlgorithmException, CMSException, Exception { // TODO if (signerInfs.isEmpty()){ // /* RFC 3852 5.2 // * "In the degenerate case where there are no signers, the // * EncapsulatedContentInfo value being "signed" is irrelevant. In this // * case, the content type within the EncapsulatedContentInfo value being // * "signed" MUST be id-data (as defined in section 4), and the content // * field of the EncapsulatedContentInfo value MUST be omitted." // *//*w ww.j a va 2s.c o m*/ // if (encapsulate) { // throw new IllegalArgumentException("no signers, encapsulate must be false"); // } if (!DATA.equals(eContentType)) { // throw new IllegalArgumentException("no signers, eContentType must be id-data"); // } // } // if (!DATA.equals(eContentType)) { // /* RFC 3852 5.3 // * [The 'signedAttrs']... // * field is optional, but it MUST be present if the content type of // * the EncapsulatedContentInfo value being signed is not id-data. // */ // // TODO signedAttrs must be present for all signers // } ASN1EncodableVector digestAlgs = new ASN1EncodableVector(); ASN1EncodableVector signerInfos = new ASN1EncodableVector(); digests.clear(); // clear the current preserved digest state Iterator it = _signers.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); digestAlgs.add(CMSUtils.fixAlgID(signer.getDigestAlgorithmID())); signerInfos.add(signer.toSignerInfo()); } boolean isCounterSignature = (eContentType == null); ASN1ObjectIdentifier contentTypeOID = isCounterSignature ? CMSObjectIdentifiers.data : new ASN1ObjectIdentifier(eContentType); for (SignerInfo signerInfo : signerInfoList) { digestAlgs.add(signerInfo.getDigestAlgorithm()); signerInfos.add(signerInfo); } ASN1Set certificates = null; if (!certs.isEmpty()) certificates = CMSUtils.createBerSetFromList(certs); ASN1Set certrevlist = null; if (!crls.isEmpty()) certrevlist = CMSUtils.createBerSetFromList(crls); ASN1OctetString octs = null; if (encapsulate && content != null) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); content.write(bOut); octs = new BERConstructedOctetString(bOut.toByteArray()); } ContentInfo encInfo = new ContentInfo(contentTypeOID, octs); SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist, new DERSet(signerInfos)); ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd); return new CMSSignedData(content, contentInfo); }
From source file:org.xipki.pki.ca.server.impl.scep.Scep.java
License:Open Source License
private PkiMessage doServicePkiOperation(final CMSSignedData requestContent, final DecodedPkiMessage req, final String certProfileName, final String msgId, final AuditEvent event) throws MessageDecodingException, OperationException { ParamUtil.requireNonNull("requestContent", requestContent); ParamUtil.requireNonNull("req", req); String tid = req.getTransactionId().getId(); // verify and decrypt the request audit(event, CaAuditConstants.NAME_tid, tid); if (req.getFailureMessage() != null) { audit(event, CaAuditConstants.NAME_SCEP_failureMessage, req.getFailureMessage()); }//from w ww. j av a 2 s .c om Boolean bo = req.isSignatureValid(); if (bo != null && !bo.booleanValue()) { audit(event, CaAuditConstants.NAME_SCEP_signature, "invalid"); } bo = req.isDecryptionSuccessful(); if (bo != null && !bo.booleanValue()) { audit(event, CaAuditConstants.NAME_SCEP_decryption, "failed"); } PkiMessage rep = new PkiMessage(req.getTransactionId(), MessageType.CertRep, Nonce.randomNonce()); rep.setRecipientNonce(req.getSenderNonce()); if (req.getFailureMessage() != null) { rep.setPkiStatus(PkiStatus.FAILURE); rep.setFailInfo(FailInfo.badRequest); } bo = req.isSignatureValid(); if (bo != null && !bo.booleanValue()) { rep.setPkiStatus(PkiStatus.FAILURE); rep.setFailInfo(FailInfo.badMessageCheck); } bo = req.isDecryptionSuccessful(); if (bo != null && !bo.booleanValue()) { rep.setPkiStatus(PkiStatus.FAILURE); rep.setFailInfo(FailInfo.badRequest); } Date signingTime = req.getSigningTime(); if (maxSigningTimeBiasInMs > 0) { boolean isTimeBad = false; if (signingTime == null) { isTimeBad = true; } else { long now = System.currentTimeMillis(); long diff = now - signingTime.getTime(); if (diff < 0) { diff = -1 * diff; } isTimeBad = diff > maxSigningTimeBiasInMs; } if (isTimeBad) { rep.setPkiStatus(PkiStatus.FAILURE); rep.setFailInfo(FailInfo.badTime); } } // end if // check the digest algorithm String oid = req.getDigestAlgorithm().getId(); ScepHashAlgoType hashAlgoType = ScepHashAlgoType.forNameOrOid(oid); if (hashAlgoType == null) { LOG.warn("tid={}: unknown digest algorithm {}", tid, oid); rep.setPkiStatus(PkiStatus.FAILURE); rep.setFailInfo(FailInfo.badAlg); } else { boolean supported = false; if (hashAlgoType == ScepHashAlgoType.SHA1) { if (caCaps.containsCapability(CaCapability.SHA1)) { supported = true; } } else if (hashAlgoType == ScepHashAlgoType.SHA256) { if (caCaps.containsCapability(CaCapability.SHA256)) { supported = true; } } else if (hashAlgoType == ScepHashAlgoType.SHA512) { if (caCaps.containsCapability(CaCapability.SHA512)) { supported = true; } } if (!supported) { LOG.warn("tid={}: unsupported digest algorithm {}", tid, oid); rep.setPkiStatus(PkiStatus.FAILURE); rep.setFailInfo(FailInfo.badAlg); } } // check the content encryption algorithm ASN1ObjectIdentifier encOid = req.getContentEncryptionAlgorithm(); if (CMSAlgorithm.DES_EDE3_CBC.equals(encOid)) { if (!caCaps.containsCapability(CaCapability.DES3)) { LOG.warn("tid={}: encryption with DES3 algorithm is not permitted", tid, encOid); rep.setPkiStatus(PkiStatus.FAILURE); rep.setFailInfo(FailInfo.badAlg); } } else if (AES_ENC_ALGOS.contains(encOid)) { if (!caCaps.containsCapability(CaCapability.AES)) { LOG.warn("tid={}: encryption with AES algorithm {} is not permitted", tid, encOid); rep.setPkiStatus(PkiStatus.FAILURE); rep.setFailInfo(FailInfo.badAlg); } } else { LOG.warn("tid={}: encryption with algorithm {} is not permitted", tid, encOid); rep.setPkiStatus(PkiStatus.FAILURE); rep.setFailInfo(FailInfo.badAlg); } if (rep.getPkiStatus() == PkiStatus.FAILURE) { return rep; } X509Ca ca; try { ca = caManager.getX509Ca(caName); } catch (CaMgmtException ex) { LogUtil.error(LOG, ex, tid + "=" + tid + ",could not get X509CA"); throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex); } X500Name caX500Name = ca.getCaInfo().getCertificate().getSubjectAsX500Name(); try { SignedData signedData; MessageType mt = req.getMessageType(); audit(event, CaAuditConstants.NAME_SCEP_messageType, mt.toString()); switch (mt) { case PKCSReq: case RenewalReq: case UpdateReq: CertificationRequest csr = CertificationRequest.getInstance(req.getMessageData()); X500Name reqSubject = csr.getCertificationRequestInfo().getSubject(); String reqSubjectText = X509Util.getRfc4519Name(reqSubject); LOG.info("tid={}, subject={}", tid, reqSubjectText); CmpControl cmpControl = caManager.getCmpControlObject(ca.getCaInfo().getCmpControlName()); if (!caManager.getSecurityFactory().verifyPopo(csr, cmpControl.getPopoAlgoValidator())) { LOG.warn("tid={}, POPO verification failed", tid); throw FailInfoException.BAD_MESSAGE_CHECK; } CertificationRequestInfo csrReqInfo = csr.getCertificationRequestInfo(); X509Certificate reqSignatureCert = req.getSignatureCert(); boolean selfSigned = reqSignatureCert.getSubjectX500Principal() .equals(reqSignatureCert.getIssuerX500Principal()); String cn = X509Util.getCommonName(csrReqInfo.getSubject()); if (cn == null) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "tid=" + tid + ": no CommonName in requested subject"); } String user = null; boolean authenticatedByPwd = false; String challengePwd = CaUtil.getChallengePassword(csrReqInfo); if (challengePwd != null) { String[] strs = challengePwd.split(":"); if (strs != null && strs.length == 2) { user = strs[0]; String password = strs[1]; authenticatedByPwd = ca.authenticateUser(user, password.getBytes()); if (!authenticatedByPwd) { LOG.warn("tid={}: could not verify the challengePassword", tid); throw FailInfoException.BAD_REQUEST; } } else { LOG.warn("tid={}: ignore challengePassword since it does not has the" + " format <user>:<password>", tid); } } // end if if (selfSigned) { if (MessageType.PKCSReq != mt) { LOG.warn("tid={}: self-signed certificate is not permitted for" + " messageType {}", tid, mt); throw FailInfoException.BAD_REQUEST; } if (user == null) { LOG.warn("tid={}: could not extract user & password from challengePassword" + ", which are required for self-signed signature certificate", tid); throw FailInfoException.BAD_REQUEST; } checkCommonName(ca, user, cn); } else { if (user == null) { // up to draft-nourse-scep-23 the client sends all messages to enroll // certificate via MessageType PKCSReq KnowCertResult knowCertRes = ca.knowsCertificate(reqSignatureCert); if (!knowCertRes.isKnown()) { LOG.warn("tid={}: signature certificate is not trusted by the CA", tid); throw FailInfoException.BAD_REQUEST; } user = knowCertRes.getUser(); } // end if // only the same subject is permitted String cnInSignatureCert = X509Util.getCommonName( X500Name.getInstance(reqSignatureCert.getSubjectX500Principal().getEncoded())); boolean b2 = cn.equals(cnInSignatureCert); if (!b2) { if (user != null) { checkCommonName(ca, user, cn); } else { LOG.warn("tid={}: signature certificate is not trusted and {}", tid, "no challengePassword is contained in the request"); throw FailInfoException.BAD_REQUEST; } } // end if } // end if byte[] tidBytes = getTransactionIdBytes(tid); Extensions extensions = CaUtil.getExtensions(csrReqInfo); CertTemplateData certTemplateData = new CertTemplateData(csrReqInfo.getSubject(), csrReqInfo.getSubjectPublicKeyInfo(), (Date) null, (Date) null, extensions, certProfileName); X509CertificateInfo cert = ca.generateCertificate(certTemplateData, true, null, user, RequestType.SCEP, tidBytes, msgId); /* Don't save SCEP message, since it contains password in plaintext if (ca.getCaInfo().isSaveRequest() && cert.getCert().getCertId() != null) { byte[] encodedRequest; try { encodedRequest = requestContent.getEncoded(); } catch (IOException ex) { LOG.warn("could not encode request"); encodedRequest = null; } if (encodedRequest != null) { long reqId = ca.addRequest(encodedRequest); ca.addRequestCert(reqId, cert.getCert().getCertId()); } }*/ signedData = buildSignedData(cert.getCert().getCert()); break; case CertPoll: IssuerAndSubject is = IssuerAndSubject.getInstance(req.getMessageData()); audit(event, CaAuditConstants.NAME_issuer, X509Util.getRfc4519Name(is.getIssuer())); audit(event, CaAuditConstants.NAME_subject, X509Util.getRfc4519Name(is.getSubject())); ensureIssuedByThisCa(caX500Name, is.getIssuer()); signedData = pollCert(ca, is.getSubject(), req.getTransactionId()); break; case GetCert: IssuerAndSerialNumber isn = IssuerAndSerialNumber.getInstance(req.getMessageData()); BigInteger serial = isn.getSerialNumber().getPositiveValue(); audit(event, CaAuditConstants.NAME_issuer, X509Util.getRfc4519Name(isn.getName())); audit(event, CaAuditConstants.NAME_serial, LogUtil.formatCsn(serial)); ensureIssuedByThisCa(caX500Name, isn.getName()); signedData = getCert(ca, isn.getSerialNumber().getPositiveValue()); break; case GetCRL: isn = IssuerAndSerialNumber.getInstance(req.getMessageData()); serial = isn.getSerialNumber().getPositiveValue(); audit(event, CaAuditConstants.NAME_issuer, X509Util.getRfc4519Name(isn.getName())); audit(event, CaAuditConstants.NAME_serial, LogUtil.formatCsn(serial)); ensureIssuedByThisCa(caX500Name, isn.getName()); signedData = getCrl(ca, serial); break; default: LOG.error("unknown SCEP messageType '{}'", req.getMessageType()); throw FailInfoException.BAD_REQUEST; } // end switch ContentInfo ci = new ContentInfo(CMSObjectIdentifiers.signedData, signedData); rep.setMessageData(ci); rep.setPkiStatus(PkiStatus.SUCCESS); } catch (FailInfoException ex) { LogUtil.error(LOG, ex); rep.setPkiStatus(PkiStatus.FAILURE); rep.setFailInfo(ex.getFailInfo()); } return rep; }
From source file:passwdmanager.hig.no.lds.DG_SOD.java
private static ContentInfo createContentInfo(String digestAlgorithm, Map<Integer, byte[]> dataGroupHashes) throws NoSuchAlgorithmException { DataGroupHash[] dataGroupHashesArray = new DataGroupHash[dataGroupHashes.size()]; int i = 0;/*from ww w .j ava2 s .c o m*/ for (int dataGroupNumber : dataGroupHashes.keySet()) { byte[] hashBytes = dataGroupHashes.get(dataGroupNumber); DataGroupHash hash = new DataGroupHash(dataGroupNumber, new DEROctetString(hashBytes)); dataGroupHashesArray[i++] = hash; } AlgorithmIdentifier digestAlgorithmIdentifier = new AlgorithmIdentifier( lookupOIDByMnemonic(digestAlgorithm), new DERNull()); LDSSecurityObject sObject2 = new LDSSecurityObject(digestAlgorithmIdentifier, dataGroupHashesArray); return new ContentInfo(ICAO_SOD_OID, new DEROctetString(sObject2)); }