List of usage examples for org.bouncycastle.asn1 ASN1EncodableVector ASN1EncodableVector
public ASN1EncodableVector()
From source file:bluecrystal.bcdeps.helper.DerEncoder.java
License:Open Source License
private void buildContentInfo(final ASN1EncodableVector body, int size) { // ------ Content Info ASN1EncodableVector contentInfoVector = new ASN1EncodableVector(); contentInfoVector.add(new DERObjectIdentifier(ID_PKCS7_DATA)); // 4 OID if (size != DETACHED) { byte[] content = new byte[size]; for (int i = 0; i < size; i++) { content[i] = (byte) 0xba; }/*from ww w. j a v a 2 s .com*/ contentInfoVector.add(new DERTaggedObject(0, new DEROctetString(content))); } // CONTENT INFO final DERSequence contentinfo = new DERSequence(contentInfoVector); // 3 // SEQ body.add(contentinfo); }
From source file:bluecrystal.bcdeps.helper.DerEncoder.java
License:Open Source License
private void buildDigestAlg(final ASN1EncodableVector body, String hashId) { // ---------- algoritmos de digest final ASN1EncodableVector algos = new ASN1EncodableVector(); algos.add(new DERObjectIdentifier(hashId)); // 4 OID algos.add(new DERNull()); // 4 NULL final ASN1EncodableVector algoSet = new ASN1EncodableVector(); algoSet.add(new DERSequence(algos)); final DERSet digestAlgorithms = new DERSet(algoSet); // 2 // SET/*ww w. j a v a 2 s . c om*/ body.add(digestAlgorithms); }
From source file:bluecrystal.bcdeps.helper.DerEncoder.java
License:Open Source License
private void buildDigestAlg(final ASN1EncodableVector body, List<String> listHashId) { // ---------- algoritmos de digest final ASN1EncodableVector algos = new ASN1EncodableVector(); for (String next : listHashId) { algos.add(new DERObjectIdentifier(next)); // 4 OID algos.add(new DERNull()); // 4 NULL }//from w ww . j a v a 2 s .c o m final ASN1EncodableVector algoSet = new ASN1EncodableVector(); algoSet.add(new DERSequence(algos)); final DERSet digestAlgorithms = new DERSet(algoSet); // 2 // SET body.add(digestAlgorithms); }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") static protected SignedData includeCrls(byte[] assinatura, Collection crls) throws IOException, Exception, SecurityException, CRLException, NoSuchProviderException, NoSuchAlgorithmException { org.bouncycastle.asn1.pkcs.SignedData pkcs7 = pkcs7SignedData(assinatura); ContentInfo content = new ContentInfo(CMSObjectIdentifiers.data, null); SignedData signedCms = new SignedData(pkcs7.getDigestAlgorithms(), content, pkcs7.getCertificates(), pkcs7.getCRLs(), pkcs7.getSignerInfos()); ASN1EncodableVector vec = new ASN1EncodableVector(); for (X509CRLObject crl : (Collection<X509CRLObject>) crls) vec.add(ASN1Primitive.fromByteArray(crl.getEncoded())); DERSet set = new DERSet(vec); // for (X509CRLObject crl : (Collection<X509CRLObject>) crls) // set.addObject(ASN1Object.fromByteArray(crl.getEncoded())); SignedData signedCmsWithCrls = new SignedData(signedCms.getDigestAlgorithms(), signedCms.getEncapContentInfo(), signedCms.getCertificates(), set, signedCms.getSignerInfos()); signedCmsWithCrls.getCertificates(); signedCmsWithCrls.getCRLs();/* w w w . ja va2 s.c om*/ return signedCmsWithCrls; }
From source file:br.gov.jfrj.siga.cd.TimeStamper.java
License:Open Source License
/** * Modyfy PKCS#7 data by adding timestamp * /*from w w w .ja va 2s . com*/ * (at) param signedData (at) throws Exception */ public static CMSSignedData addTimestamp(CMSSignedData signedData) throws Exception { Collection ss = signedData.getSignerInfos().getSigners(); SignerInformation si = (SignerInformation) ss.iterator().next(); TimeStampToken tok = getTimeStampToken(si.getSignature()); // CertStore certs = tok.getCertificatesAndCRLs("Collection", "BC"); Store certs = tok.getCertificates(); Store certsAndCrls = AssinaturaDigital.buscarCrlParaCadaCertificado(certs); CMSSignedData cmssdcrl = CMSSignedData.replaceCertificatesAndCRLs(tok.toCMSSignedData(), certsAndCrls, certsAndCrls, certsAndCrls); tok = new TimeStampToken(cmssdcrl); ASN1InputStream asn1InputStream = new ASN1InputStream(tok.getEncoded()); ASN1Primitive tstDER = asn1InputStream.readObject(); DERSet ds = new DERSet(tstDER); Attribute a = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, ds); ASN1EncodableVector dv = new ASN1EncodableVector(); dv.add(a); AttributeTable at = new AttributeTable(dv); si = SignerInformation.replaceUnsignedAttributes(si, at); ss.clear(); ss.add(si); SignerInformationStore sis = new SignerInformationStore(ss); signedData = CMSSignedData.replaceSigners(signedData, sis); return signedData; }
From source file:br.ufpb.dicomflow.integrationAPI.mail.AbstractMailSender.java
License:Open Source License
private Message signAndEcrypt(Message message, X509Certificate signCert, X509Certificate encryptCert, PrivateKey privateKey) throws Exception { MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mailcap.addMailcap(//from w ww. ja v a2 s .c o m "application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature"); mailcap.addMailcap( "application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime"); mailcap.addMailcap( "application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature"); mailcap.addMailcap( "application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime"); mailcap.addMailcap( "multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed"); CommandMap.setDefaultCommandMap(mailcap); /* Create the Signer - SMIMESignedGenerator */ SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); ASN1EncodableVector attributes = new ASN1EncodableVector(); attributes.add(new SMIMEEncryptionKeyPreferenceAttribute( new IssuerAndSerialNumber(new X500Name(((X509Certificate) signCert).getIssuerDN().getName()), ((X509Certificate) signCert).getSerialNumber()))); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); SMIMESignedGenerator signer = new SMIMESignedGenerator(); signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder() .setSignedAttributeGenerator(new AttributeTable(attributes)) .build("DSA".equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA", privateKey, signCert)); /* Add the list of certs to the generator */ List certList = new ArrayList(); certList.add(signCert); Store certs = new JcaCertStore(certList); signer.addCertificates(certs); /* Sign the message */ MimeMultipart mm = signer.generate((MimeMessage) message); MimeMessage signedMessage = new MimeMessage(message.getSession()); /* Set all original MIME headers in the signed message */ Enumeration headers = ((MimeMessage) message).getAllHeaderLines(); while (headers.hasMoreElements()) { signedMessage.addHeaderLine((String) headers.nextElement()); } /* Set the content of the signed message */ signedMessage.setContent(mm); signedMessage.saveChanges(); /* Create the encrypter - SMIMEEnvelopedGenerator */ SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator(); encrypter.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(encryptCert)); /* Encrypt the message */ MimeBodyPart encryptedPart = encrypter.generate(signedMessage, new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC).build()); /* * Create a new MimeMessage that contains the encrypted and signed * content */ ByteArrayOutputStream out = new ByteArrayOutputStream(); encryptedPart.writeTo(out); MimeMessage encryptedMessage = new MimeMessage(message.getSession(), new ByteArrayInputStream(out.toByteArray())); /* Set all original MIME headers in the encrypted message */ headers = ((MimeMessage) message).getAllHeaderLines(); while (headers.hasMoreElements()) { String headerLine = (String) headers.nextElement(); /* * Make sure not to override any content-* headers from the * original message */ if (!Strings.toLowerCase(headerLine).startsWith("content-")) { encryptedMessage.addHeaderLine(headerLine); } } return encryptedMessage; }
From source file:ca.nrc.cadc.cred.CertUtil.java
License:Open Source License
/** * Method that generates an X509 proxy certificate * //w w w . j a v a2s.c om * @param csr CSR for the certificate * @param lifetime lifetime of the certificate in SECONDS * @param chain certificate used to sign the proxy certificate * @return generated proxy certificate * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws InvalidKeyException * @throws CertificateParsingException * @throws CertificateEncodingException * @throws SignatureException * @throws CertificateNotYetValidException * @throws CertificateExpiredException */ public static X509Certificate generateCertificate(PKCS10CertificationRequest csr, int lifetime, X509CertificateChain chain) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, CertificateParsingException, CertificateEncodingException, SignatureException, CertificateExpiredException, CertificateNotYetValidException { X509Certificate issuerCert = chain.getChain()[0]; PrivateKey issuerKey = chain.getPrivateKey(); Security.addProvider(new BouncyCastleProvider()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(issuerCert.getSubjectX500Principal()); // generate the proxy DN as the issuerDN + CN=random number Random rand = new Random(); String issuerDN = issuerCert.getSubjectX500Principal().getName(X500Principal.RFC2253); String delegDN = String.valueOf(Math.abs(rand.nextInt())); String proxyDn = "CN=" + delegDN + "," + issuerDN; certGen.setSubjectDN(new X500Principal(proxyDn)); // set validity GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT")); // Start date. Allow for a sixty five minute clock skew here. date.add(Calendar.MINUTE, -65); Date beforeDate = date.getTime(); for (X509Certificate currentCert : chain.getChain()) { if (beforeDate.before(currentCert.getNotBefore())) { beforeDate = currentCert.getNotBefore(); } } certGen.setNotBefore(beforeDate); // End date. // If hours = 0, then cert lifetime is set to that of user cert if (lifetime <= 0) { // set the validity of certificates as the minimum // of the certificates in the chain Date afterDate = issuerCert.getNotAfter(); for (X509Certificate currentCert : chain.getChain()) { if (afterDate.after(currentCert.getNotAfter())) { afterDate = currentCert.getNotAfter(); } } certGen.setNotAfter(afterDate); } else { // check the validity of the signing certificate date.add(Calendar.MINUTE, 5); date.add(Calendar.SECOND, lifetime); for (X509Certificate currentCert : chain.getChain()) { currentCert.checkValidity(date.getTime()); } certGen.setNotAfter(date.getTime()); } certGen.setPublicKey(csr.getPublicKey()); // TODO: should be able to get signature algorithm from the csr, but... obtuse certGen.setSignatureAlgorithm(DEFAULT_SIGNATURE_ALGORITHM); // extensions // add ProxyCertInfo extension to the new cert certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuerCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(csr.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); // add the Proxy Certificate Information // I expect this code to be removed once support to proxy // certificates is provided in Bouncy Castle. // create a proxy policy // types of proxy certificate policies - see RFC3820 // impersonates the user final DERObjectIdentifier IMPERSONATION = new DERObjectIdentifier("1.3.6.1.5.5.7.21.1"); // independent // final DERObjectIdentifier INDEPENDENT = new // DERObjectIdentifier( // "1.3.6.1.5.5.7.21.2"); // defined by a policy language // final DERObjectIdentifier LIMITED = new DERObjectIdentifier( // "1.3.6.1.4.1.3536.1.1.1.9"); ASN1EncodableVector policy = new ASN1EncodableVector(); policy.add(IMPERSONATION); // pathLengthConstr (RFC3820) // The pCPathLenConstraint field, if present, specifies the // maximum // depth of the path of Proxy Certificates that can be signed by // this // Proxy Certificate. A pCPathLenConstraint of 0 means that this // certificate MUST NOT be used to sign a Proxy Certificate. If // the // pCPathLenConstraint field is not present then the maximum proxy // path // length is unlimited. End entity certificates have unlimited // maximum // proxy path lengths. // DERInteger pathLengthConstr = new DERInteger(100); // create the proxy certificate information ASN1EncodableVector vec = new ASN1EncodableVector(); // policy.add(pathLengthConstr); vec.add(new DERSequence(policy)); // OID final DERObjectIdentifier OID = new DERObjectIdentifier("1.3.6.1.5.5.7.1.14"); certGen.addExtension(OID, true, new DERSequence(vec)); return certGen.generate(issuerKey, "BC"); }
From source file:ca.trustpoint.m2m.AuthorityKeyIdentifier.java
License:Apache License
/** * Returns the DER encoding of this instance. * * @return The DER encoding of this instance. * @throws IOException if this instance cannot be encoded. *//*from w w w . j ava 2 s. c o m*/ public byte[] getEncoded() throws IOException { if (!isValid()) { throw new IOException("AuthKeyId is not valid."); } ASN1EncodableVector values = new ASN1EncodableVector(); if (keyIdentifier != null) { DEROctetString idOctets = new DEROctetString(keyIdentifier); values.add(new DERTaggedObject(false, INDEX_KEY_IDENTIFIER, idOctets)); } if (certificateIssuer != null) { ASN1TaggedObject encodedIssuer = DERTaggedObject.getInstance(certificateIssuer.getEncoded()); values.add(new DERTaggedObject(true, INDEX_AUTH_CERT_ISSUER, encodedIssuer)); } if (certificateSerialNumber != null) { DEROctetString serialOctets = new DEROctetString(certificateSerialNumber.toByteArray()); values.add(new DERTaggedObject(false, INDEX_AUTH_CERT_SERIAL_NUM, serialOctets)); } return (new DERSequence(values).getEncoded()); }
From source file:ca.trustpoint.m2m.M2mCertificate.java
License:Apache License
/** * Returns the DER encoded to be signed certificate data. This is what would be sent to a CA for * signing, or the data that will be verified with the signature. * * @return The DER encoded to be signed certificate data. * @throws IOException if the encoding fails. *///from w ww. java 2s.c o m public byte[] getTBSCertificate() throws IOException { if (!isTbsCertificateValid()) { throw new IOException("One or more TBS certificate fields are invalid."); } ASN1EncodableVector elements = new ASN1EncodableVector(); /* * Since the default is v1 (0), we do not need to explicitly add this to the ASN.1 output. * * elements.add( new DERTaggedObject( false, TbsCertificateFields.VERSION.getTagNumber(), new * ASN1Integer(VERSION))); */ elements.add(new DERTaggedObject(false, TbsCertificateFields.SERIAL_NUMBER.getTagNumber(), new DEROctetString(serialNumber))); if (caKeyDefinition != null) { if (caKeyDefinition.getAlgorithm() != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.CA_ALGORITHM.getTagNumber(), ASN1Primitive.fromByteArray(caKeyDefinition.getEncodedAlgorithm()))); } if (caKeyDefinition.getParameters() != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.CA_ALGORITHM_PARAMETERS.getTagNumber(), ASN1Primitive.fromByteArray(caKeyDefinition.getEncodedParameters()))); } } if (issuer != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.ISSUER.getTagNumber(), DERSequence.getInstance(issuer.getEncoded()))); } if (validFrom != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.VALID_FROM.getTagNumber(), // We record seconds, not milliseconds, hence the / 1000 new DEROctetString(BigInteger.valueOf(validFrom.getTime() / 1000).toByteArray()))); } if (validDuration != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.VALID_DURATION.getTagNumber(), new DEROctetString(BigInteger.valueOf(validDuration.intValue()).toByteArray()))); } elements.add(new DERTaggedObject(false, TbsCertificateFields.SUBJECT.getTagNumber(), DERSequence.getInstance(subject.getEncoded()))); if (publicKeyDefinition != null) { if (publicKeyDefinition.getAlgorithm() != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.PUBLIC_KEY_ALGORITHM.getTagNumber(), ASN1Primitive.fromByteArray(publicKeyDefinition.getEncodedAlgorithm()))); } if (publicKeyDefinition.getParameters() != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.PUBLIC_KEY_ALGORITHM_PARAMETERS.getTagNumber(), ASN1Primitive.fromByteArray(publicKeyDefinition.getEncodedParameters()))); } } if (publicKey != null) { byte[] publicKeyBytes = KeyConversionUtils.convertEcPublicKeyToRawBytes(publicKey, isPublicKeyCompressed); elements.add(new DERTaggedObject(false, TbsCertificateFields.PUBLIC_KEY.getTagNumber(), new DEROctetString(publicKeyBytes))); } if (authorityKeyIdentifier != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.AUTHORITY_KEY_ID.getTagNumber(), ASN1Primitive.fromByteArray(authorityKeyIdentifier.getEncoded()))); } if (subjectKeyIdentifier != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.SUBJECT_KEY_ID.getTagNumber(), new DEROctetString(subjectKeyIdentifier))); } if (keyUsage != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.KEY_USAGE.getTagNumber(), ASN1Primitive.fromByteArray(keyUsage.getEncoded()))); } if (basicConstraints != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.BASIC_CONSTRAINTS.getTagNumber(), new ASN1Integer(basicConstraints.intValue()))); } if (certificatePolicy != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.CERTIFICATE_POLICY.getTagNumber(), new ASN1ObjectIdentifier(certificatePolicy))); } if (subjectAlternativeName != null) { elements.add(new DERTaggedObject(true, TbsCertificateFields.SUBJECT_ALTERNATE_NAME.getTagNumber(), DERTaggedObject.getInstance(subjectAlternativeName.getEncoded()))); } if (issuerAlternativeName != null) { elements.add(new DERTaggedObject(true, TbsCertificateFields.ISSUER_ALTERNATE_NAME.getTagNumber(), DERTaggedObject.getInstance(issuerAlternativeName.getEncoded()))); } if (extendedKeyUsage != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.EXTENDED_KEY_USAGE.getTagNumber(), new ASN1ObjectIdentifier(extendedKeyUsage))); } if (authenticationInfoAccessOcsp != null) { elements.add( new DERTaggedObject(false, TbsCertificateFields.AUTHENTICATION_INFO_ACCESS_OCSP.getTagNumber(), new DERIA5String(authenticationInfoAccessOcsp.toString()))); } if (crlDistributionPointUri != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.CRL_DISTRIBUTION_POINT_URI.getTagNumber(), new DERIA5String(crlDistributionPointUri.toString()))); } if (!extensions.isEmpty()) { ASN1EncodableVector toBeEncodedExtensions = new ASN1EncodableVector(); for (Extension extension : extensions) { toBeEncodedExtensions.add(new DERSequence(extension.getEncoded())); } elements.add(new DERTaggedObject(false, TbsCertificateFields.EXTENSIONS.getTagNumber(), new DERSequence(toBeEncodedExtensions))); } return ((new DERSequence(elements)).getEncoded()); }
From source file:ca.trustpoint.m2m.M2mCertificate.java
License:Apache License
@Override public byte[] getEncoded() throws CertificateEncodingException { ASN1EncodableVector elements = new ASN1EncodableVector(); if (!isTbsCertificateValid()) { throw new CertificateEncodingException("TBS certificate is invalid."); } else if ((caCalcValue == null) || (caCalcValue.length == 0)) { throw new CertificateEncodingException("Signature or reconstruction value must be present."); }//from w ww. j av a2 s. com try { elements.add(new DERTaggedObject(false, CertificateFields.TBS_CERTIFICATE.getTagNumber(), DERSequence.fromByteArray(getTBSCertificate()))); } catch (IOException ex) { throw new CertificateEncodingException("Could not encode TBS certificate fields.", ex); } elements.add(new DERTaggedObject(false, CertificateFields.CA_CALC_VALUE.getTagNumber(), new DEROctetString(caCalcValue))); DERApplicationSpecific certificate = null; try { certificate = new DERApplicationSpecific(false, APPLICATION_TAG_NUMBER, new DERSequence(elements)); } catch (IOException ex) { throw new CertificateEncodingException("Could not construct ASN.1 certificate.", ex); } byte[] encodedBytes = null; try { encodedBytes = certificate.getEncoded(); } catch (IOException ex) { throw new CertificateEncodingException("Could not encode certificate.", ex); } return encodedBytes; }