List of usage examples for org.bouncycastle.asn1 BERConstructedOctetString BERConstructedOctetString
public BERConstructedOctetString(ASN1Encodable obj)
From source file:ee.sk.digidoc.factory.BouncyCastleNotaryFactory.java
License:Open Source License
/** * Method for creating CertificateID for OCSP request * @param signersCert/* ww w. j a v a2 s .c o m*/ * @param caCert * @param provider * @return * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws CertificateEncodingException */ private CertificateID creatCertReq(X509Certificate signersCert, X509Certificate caCert) throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException, DigiDocException { // TODO: checks this OID !!! MessageDigest digest = MessageDigest.getInstance("1.3.14.3.2.26", "BC"); if (m_logger.isDebugEnabled()) m_logger.debug("CA cert: " + ((caCert != null) ? caCert.toString() : "NULL")); X509Principal issuerName = PrincipalUtil.getSubjectX509Principal(caCert); if (m_logger.isDebugEnabled()) m_logger.debug("CA issuer: " + ((issuerName != null) ? issuerName.getName() : "NULL")); //Issuer name hash digest.update(issuerName.getEncoded()); ASN1OctetString issuerNameHash = new BERConstructedOctetString(digest.digest()); //Issuer key hash will be readed out from X509extendions // 4 first bytes are not useful for me, oid 2.5.29.15 contains keyid byte[] arr = caCert.getExtensionValue("2.5.29.14"); if (m_logger.isDebugEnabled()) m_logger.debug("Issuer key hash: " + ((arr != null) ? arr.length : 0)); if (arr == null || arr.length == 0) throw new DigiDocException(DigiDocException.ERR_CA_CERT_READ, "CA certificate has no SubjectKeyIdentifier extension!", null); byte[] arr2 = new byte[arr.length - 4]; System.arraycopy(arr, 4, arr2, 0, arr2.length); ASN1OctetString issuerKeyHash = new BERConstructedOctetString(arr2); CertID cerid = new CertID(new AlgorithmIdentifier("1.3.14.3.2.26"), issuerNameHash, issuerKeyHash, new DERInteger(signersCert.getSerialNumber())); return new CertificateID(cerid); }
From source file:ee.sk.digidoc.factory.BouncyCastleNotaryFactory.java
License:Open Source License
/** * Creates a new OCSP request/*from w ww . jav a 2 s. c o m*/ * @param nonce 128 byte RSA+SHA1 signatures digest * Use null if you want to verify only the certificate * and this is not related to any signature * @param signersCert signature owners cert * @param caCert CA cert for this signer * @param bSigned flag signed request or not */ private OCSPReq createOCSPRequest(byte[] nonce, X509Certificate signersCert, X509Certificate caCert, boolean bSigned) throws DigiDocException { OCSPReq req = null; OCSPReqGenerator ocspRequest = new OCSPReqGenerator(); try { //Create certificate id, for OCSP request CertificateID certId = creatCertReq(signersCert, caCert); if (m_logger.isDebugEnabled()) m_logger.debug("Request for: " + certId.getHashAlgOID() + " serial: " + certId.getSerialNumber() + " issuer: " + Base64Util.encode(certId.getIssuerKeyHash()) + " subject: " + Base64Util.encode(certId.getIssuerNameHash())); ocspRequest.addRequest(certId); if (nonce != null) { ASN1OctetString ocset = new BERConstructedOctetString(nonce); X509Extension ext = new X509Extension(false, ocset); //nonce Identifier DERObjectIdentifier nonceIdf = new DERObjectIdentifier(nonceOid); Hashtable tbl = new Hashtable(1); tbl.put(nonceIdf, ext); // create extendions, with one extendion(NONCE) X509Extensions extensions = new X509Extensions(tbl); ocspRequest.setRequestExtensions(extensions); } //X509Name n = new X509Name() GeneralName name = null; if (bSigned) { if (m_logger.isDebugEnabled()) m_logger.debug("SignCert: " + ((m_signCert != null) ? m_signCert.toString() : "NULL")); name = new GeneralName(PrincipalUtil.getSubjectX509Principal(m_signCert)); } else { name = new GeneralName(PrincipalUtil.getSubjectX509Principal(signersCert)); // VS: Mihhails patch for accepting Hansa's cert /* Hashtable myLookUp=new Hashtable(X509Name.DefaultLookUp); DERObjectIdentifier SERIALNUMBER = new DERObjectIdentifier("2.5.4.5"); myLookUp.put(SERIALNUMBER, "SERIALNUMBER"); name = new GeneralName(new X509Name(X509Name.DefaultReverse, myLookUp,signersCert.getSubjectDN().toString())); */ } ocspRequest.setRequestorName(name); if (bSigned) { // lets generate signed request X509Certificate[] chain = { m_signCert }; req = ocspRequest.generate("SHA1WITHRSA", m_signKey, chain, "BC"); if (!req.verify(m_signCert.getPublicKey(), "BC")) { m_logger.error("Verify failed"); } } else { // unsigned request req = ocspRequest.generate(); } } catch (Exception ex) { DigiDocException.handleException(ex, DigiDocException.ERR_OCSP_REQ_CREATE); } return req; }
From source file:es.uji.security.crypto.openxades.digidoc.factory.BouncyCastleNotaryFactory.java
License:Open Source License
/** * Creates a new OCSP request/*w ww. ja v a2s . c o m*/ * * @param nonce * 128 byte RSA+SHA1 signatures digest Use null if you want to verify only the * certificate and this is not related to any signature * @param signersCert * signature owners cert * @param caCert * CA cert for this signer * @param bSigned * flag signed request or not */ private OCSPReq createOCSPRequest(byte[] nonce, X509Certificate signersCert, X509Certificate caCert, boolean bSigned) throws DigiDocException { OCSPReq req = null; OCSPReqGenerator ocspRequest = new OCSPReqGenerator(); try { // Create certificate id, for OCSP request CertificateID certId = creatCertReq(signersCert, caCert); if (m_logger.isDebugEnabled()) m_logger.debug("Request for: " + certId.getHashAlgOID() + " serial: " + certId.getSerialNumber() + " issuer: " + Base64.encodeBytes(certId.getIssuerKeyHash()) + " subject: " + Base64.encodeBytes(certId.getIssuerNameHash())); ocspRequest.addRequest(certId); if (nonce != null) { ASN1OctetString ocset = new BERConstructedOctetString(nonce); X509Extension ext = new X509Extension(false, ocset); // nonce Identifier DERObjectIdentifier nonceIdf = new DERObjectIdentifier(nonceOid); Hashtable tbl = new Hashtable(1); tbl.put(nonceIdf, ext); // create extendions, with one extendion(NONCE) X509Extensions extensions = new X509Extensions(tbl); ocspRequest.setRequestExtensions(extensions); } // X509Name n = new X509Name() GeneralName name = null; if (bSigned) { if (m_logger.isDebugEnabled()) m_logger.debug("SignCert: " + ((m_signCert != null) ? m_signCert.toString() : "NULL")); name = new GeneralName(PrincipalUtil.getSubjectX509Principal(m_signCert)); } else { name = new GeneralName(PrincipalUtil.getSubjectX509Principal(signersCert)); // VS: Mihhails patch for accepting Hansa's cert /* * Hashtable myLookUp=new Hashtable(X509Name.DefaultLookUp); DERObjectIdentifier * SERIALNUMBER = new DERObjectIdentifier("2.5.4.5"); myLookUp.put(SERIALNUMBER, * "SERIALNUMBER"); name = new GeneralName(new X509Name(X509Name.DefaultReverse, * myLookUp,signersCert.getSubjectDN().toString())); */ } ocspRequest.setRequestorName(name); if (bSigned) { // lets generate signed request X509Certificate[] chain = { m_signCert }; req = ocspRequest.generate("SHA1WITHRSA", m_signKey, chain, "BC"); if (!req.verify(m_signCert.getPublicKey(), "BC")) { m_logger.error("Verify failed"); } } else { // unsigned request req = ocspRequest.generate(); } } catch (Exception e) { DigiDocException.handleException(e, DigiDocException.ERR_OCSP_REQ_CREATE); } return req; }
From source file:eu.europa.ec.markt.dss.validation.cades.CAdESSignature.java
License:Open Source License
@Override public byte[] getArchiveTimestampData(int index, Document originalDocument) throws IOException { ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream(); ContentInfo contentInfo = cmsSignedData.getContentInfo(); SignedData signedData = SignedData.getInstance(contentInfo.getContent()); /* The encapContentInfo should always be present according to the standard, but sometimes it's omitted */ // 5.4.1/*from w w w. j a v a 2s .c o m*/ if (signedData.getEncapContentInfo() == null || signedData.getEncapContentInfo().getContent() == null) { /* Detached signatures have either no encapContentInfo in signedData, or it exists but has no eContent */ if (originalDocument != null) { toTimestamp.write(originalDocument.openStream()); } else { throw new RuntimeException("Signature is detached and no original data provided."); } } else { ContentInfo content = signedData.getEncapContentInfo(); DEROctetString octet = (DEROctetString) content.getContent(); ContentInfo info2 = new ContentInfo(new ASN1ObjectIdentifier("1.2.840.113549.1.7.1"), new BERConstructedOctetString(octet.getOctets())); toTimestamp.write(info2.getEncoded()); } if (signedData.getCertificates() != null) { DEROutputStream output = new DEROutputStream(toTimestamp); output.writeObject(signedData.getCertificates()); output.close(); } if (signedData.getCRLs() != null) { toTimestamp.write(signedData.getCRLs().getEncoded()); } if (signerInformation.getUnsignedAttributes() != null) { ASN1EncodableVector original = signerInformation.getUnsignedAttributes().toASN1EncodableVector(); List<Attribute> timeStampToRemove = getTimeStampToRemove(index); ASN1EncodableVector filtered = new ASN1EncodableVector(); for (int i = 0; i < original.size(); i++) { DEREncodable enc = original.get(i); if (!timeStampToRemove.contains(enc)) { filtered.add(original.get(i)); } } SignerInformation filteredInfo = SignerInformation.replaceUnsignedAttributes(signerInformation, new AttributeTable(filtered)); toTimestamp.write(filteredInfo.toASN1Structure().getEncoded()); } return toTimestamp.toByteArray(); }
From source file:it.trento.comune.j4sign.cms.ExternalSignatureCMSSignedDataGenerator.java
License:Open Source License
/** * generate a CMS Signed Data object using the previously passed {@link ExternalSignatureSignerInfoGenerator} * objects; if encapsulate is true a copy of the message will be * included in the signature.//from w w w. jav a 2 s.c om */ public CMSSignedData generate(CMSProcessable content, boolean encapsulate) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException, InvalidAlgorithmParameterException, CertStoreException { //DEREncodableVector signerInfos = new DEREncodableVector(); //DEREncodableVector digestAlgs = new DEREncodableVector(); ASN1EncodableVector digestAlgs = new ASN1EncodableVector(); ASN1EncodableVector signerInfos = new ASN1EncodableVector(); ASN1ObjectIdentifier contentTypeOID = new ASN1ObjectIdentifier(CMSSignedDataGenerator.DATA); // // add the SignerInfo objects // Iterator it = signerInfs.iterator(); //raccoglier i certificati dei firmatari //ArrayList certList = new ArrayList(); while (it.hasNext()) { AlgorithmIdentifier digAlgId, encAlgId; ExternalSignatureSignerInfoGenerator externalSigner = (ExternalSignatureSignerInfoGenerator) it.next(); try { digAlgId = makeAlgId(externalSigner.getDigestAlgOID(), externalSigner.getDigestAlgParams()); digestAlgs.add(digAlgId); signerInfos.add(externalSigner.generate()); //certList.add(externalSigner.getCertificate()); } catch (IOException e) { throw new CMSException("encoding error.", e); } catch (CertificateEncodingException e) { throw new CMSException("error creating sid.", e); } } ASN1Set certificates = null; if (certs.size() != 0) { certificates = createBerSetFromList(certs); } /* if (certs.size() != 0) { DEREncodableVector v = new DEREncodableVector(); it = certs.iterator(); while (it.hasNext()) { v.add((DEREncodable) it.next()); } certificates = new DERSet(v); } */ ASN1Set certrevlist = null; if (crls.size() != 0) { certrevlist = createBerSetFromList(crls); } /* if (crls.size() != 0) { DEREncodableVector v = new DEREncodableVector(); it = crls.iterator(); while (it.hasNext()) { v.add((DEREncodable) it.next()); } certrevlist = new DERSet(v); } */ ASN1OctetString octs = null; if (encapsulate) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { content.write(bOut); } catch (IOException e) { throw new CMSException("encapsulation error.", e); } 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(PKCSObjectIdentifiers.signedData, sd); return new CMSSignedData(content, contentInfo); }
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 www. jav a 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); 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." // *//* www. j a v a 2 s .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); 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); }