List of usage examples for org.bouncycastle.asn1 ASN1EncodableVector ASN1EncodableVector
public ASN1EncodableVector()
From source file:ca.trustpoint.m2m.M2mCertificateFactoryTest.java
License:Apache License
@BeforeClass public static void initializeTests() throws Exception { // Construct certificate data // A full certificate M2mCertificate cert = new M2mCertificate(); // serialNumber byte[] serialNumber = Hex.decode("F964EF36"); cert.setSerialNumber(serialNumber);/*from w w w.ja va2s.co m*/ // cAAlgorithm, CAAlgParams KeyAlgorithmDefinition caKeyDefinition = new KeyAlgorithmDefinition(); caKeyDefinition.setAlgorithm(M2mSignatureAlgorithmOids.ECDSA_SHA512_SECP521R1); caKeyDefinition.setParameters(Hex.decode("102030405060708090A0B0C0E0F0")); cert.setCaKeyDefinition(caKeyDefinition); // issuer EntityName issuer = new EntityName(); issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.Country, "CA")); issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.CommonName, "MyRoot")); issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.DomainComponent, "DomC")); issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.OctetsName, "ca2f00")); cert.setIssuer(issuer); // validFrom Calendar calendar = new GregorianCalendar(2016, 7, 1); Date validFrom = calendar.getTime(); cert.setValidFrom(validFrom); // validDuration cert.setValidDuration(60 * 60 * 24 * 365); // subject EntityName subject = new EntityName(); subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.Country, "CA")); subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.CommonName, "MyTest")); subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.DomainComponent, "DomC")); subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.OctetsName, "ca2f01")); cert.setSubject(subject); // pKAlgorithm, pKAlgParams KeyAlgorithmDefinition publicKeyDefinition = new KeyAlgorithmDefinition(); publicKeyDefinition.setAlgorithm(M2mSignatureAlgorithmOids.ECDSA_SHA256_SECP256R1); publicKeyDefinition.setParameters(Hex.decode("0102030405060708090A0B0C0E0F")); cert.setPublicKeyDefinition(publicKeyDefinition); // pubKey byte[] rawPublicKey = Hex.decode("040078EF059D605AB85B6A25A6EF31A1A73A632D3CB04DC606A8CA0B58239661" + "68CFAF6131D8D9B53F6BDF6B62946EC4B41D618FA3FF7F8BBFACBFD4F64FE3C3" + "3DA9D200A47AE528DC50B6F3876D7F5BA3C082D9927751E1A8C4F934D90942B3" + "5C57DFE311B2663E8D0187AD4EDE31BF9CD2AD8317107360522FDB6975AB2CD6" + "6DC029981F"); boolean isCompressed = KeyConversionUtils.isCompressedEcPoint(rawPublicKey); cert.setIsPublicKeyCompressed(isCompressed); PublicKey publicKey = KeyConversionUtils.convertRawBytestoEcPublicKey(rawPublicKey); cert.setPublicKey(publicKey); // authKeyId AuthorityKeyIdentifier authKeyId = new AuthorityKeyIdentifier(); authKeyId.setKeyIdentifier(Hex.decode("793F0C56")); GeneralName authKeyIdIssuer = new GeneralName(GeneralNameAttributeId.DnsName, "authKeyIdIssuer"); authKeyId.setCertificateIssuer(authKeyIdIssuer); authKeyId.setCertificateSerialNumber(new BigInteger(Hex.decode("729CB27DAE30"))); cert.setAuthorityKeyIdentifier(authKeyId); // subjKeyId cert.setSubjectKeyIdentifier(Hex.decode("729CB27DAE31")); // keyUsage KeyUsage keyUsage = new KeyUsage(); keyUsage.setDigitalSignature(true); cert.setKeyUsage(keyUsage); // basicConstraints cert.setBasicConstraints(5); // certificatePolicy cert.setCertificatePolicy("1.2.66.148.0.12"); // subjectAltName GeneralName subjectAltName = new GeneralName(GeneralNameAttributeId.DnsName, "subjectAltName"); cert.setSubjectAlternativeName(subjectAltName); // issuerAltName GeneralName issuerAltName = new GeneralName(GeneralNameAttributeId.DnsName, "issuerAltName"); cert.setIssuerAlternativeName(issuerAltName); // extendedKeyUsage cert.setExtendedKeyUsage("1.3.22.174.22"); // authInfoAccessOCSP URI authInfoAccessOCSP = new URI("https://ocsptest.trustpointinnovation.com"); cert.setAuthenticationInfoAccessOcsp(authInfoAccessOCSP); // cRLDistribPointURI URI cRLDistribPointURI = new URI("https://ocsptest.trustpointinnovation.com"); cert.setCrlDistributionPointUri(cRLDistribPointURI); // x509extensions String oid1 = "1.5.24.632.0"; String oid2 = "1.5.24.632.1"; byte[] value1 = Hex.decode("003a772fb1"); byte[] value2 = Hex.decode("98f2b10e27"); cert.addExtension(oid1, true, value1); cert.addExtension(oid2, false, value2); // cACalcValue byte[] caCalcValue = Hex.decode("3081880242014F15CAF8EF38626B2C7CFA85B9544E028668290CADB45F62E215" + "3EAAF5A9D51AF5BF0D02F2C057D3856B5CBFB3529C25B8481405924039FA612D" + "422AE9A1A85591024201868D3DFE5FC2BEDD2F7468B0B17ED2708E76CD0D37C4" + "4F4D0BB88693752046FCFC56D9818B32533B8992923C2C81499400AC44FBBECD" + "6324D8AE1DD41EC73A0B2A"); cert.setCaCalcValue(caCalcValue); // get encoded data fullCertData = cert.getEncoded(); int mySignerIndex = 0; int myIssuerIndex = 1; int bluelineIndex = 2; int certsTotal = 3; // construct certificate array ASN1Encodable[] certArray = new ASN1Encodable[certsTotal]; certArray[mySignerIndex] = ASN1Primitive.fromByteArray(signerData); certArray[myIssuerIndex] = ASN1Primitive.fromByteArray(issuerData); certArray[bluelineIndex] = ASN1Primitive.fromByteArray(rootcaData); ASN1EncodableVector vCerts; // Construct PKI Path encoding input data vCerts = new ASN1EncodableVector(); vCerts.add(certArray[bluelineIndex]); vCerts.add(certArray[myIssuerIndex]); vCerts.add(certArray[mySignerIndex]); pkiPathInputData = new DERSequence(vCerts).getEncoded(); // Construct PKCS7 encoding input data ASN1EncodableVector vContentInfo = new ASN1EncodableVector(); // contentType ASN1ObjectIdentifier contentType = PKCSObjectIdentifiers.data; vContentInfo.add(contentType); // content: signedData ASN1EncodableVector vSignedData = new ASN1EncodableVector(); // version ASN1Integer sdVersion = new ASN1Integer(BigInteger.ONE); vSignedData.add(sdVersion); // digestAlgorithmIds DERSet sdDigestAlgorithmIds = new DERSet(); vSignedData.add(sdDigestAlgorithmIds); // contentInfo without content BERSequence sdContentInfo = new BERSequence(PKCSObjectIdentifiers.data); vSignedData.add(sdContentInfo); // certificates [0] IMPLICIT SET OF certificate vCerts = new ASN1EncodableVector(); vCerts.add(certArray[mySignerIndex]); vCerts.add(certArray[myIssuerIndex]); vCerts.add(certArray[bluelineIndex]); DERTaggedObject sdCertificates = new DERTaggedObject(false, 0, new DERSet(vCerts)); vSignedData.add(sdCertificates); // signerInfos DERSet sdSignerInfos = new DERSet(); vSignedData.add(sdSignerInfos); // content [0] EXPLICIT SEQUENCE signedData BERSequence signedData = new BERSequence(vSignedData); BERTaggedObject content = new BERTaggedObject(true, 0, signedData); vContentInfo.add(content); BERSequence contentInfo = new BERSequence(vContentInfo); pkcs7InputData = contentInfo.getEncoded(); // Contruct cert path data list // Certificates are store in M2MCertPath from target to trust anchor. expectedCertPathData = new byte[][] { signerData, issuerData, rootcaData }; }
From source file:ca.trustpoint.m2m.M2mCertPath.java
License:Apache License
/** * Encode the CertPath using PKIPATH format. * * @return a byte array containing the binary encoding of the PkiPath object * @exception CertificateEncodingException if an exception occurs *//*from www . j a v a 2 s .co m*/ private byte[] encodePkiPath() throws CertificateEncodingException { ListIterator<M2mCertificate> li = certificates.listIterator(certificates.size()); ASN1EncodableVector encodedList = new ASN1EncodableVector(); // Get an encodable certificate vector. The certificates are encoded in reverse order (trust // anchor to target) according to PkiPath format. while (li.hasPrevious()) { M2mCertificate certificate = li.previous(); if (isDuplicateCertificate(certificate)) { throw new CertificateEncodingException("Duplicate certificate detected in path."); } try { encodedList.add(ASN1Primitive.fromByteArray(certificate.getEncoded())); } catch (IOException ex) { throw new CertificateEncodingException("Error encoding certificate data.", ex); } } // Wrap the data in a SEQUENCE DERSequence sequence = new DERSequence(encodedList); try { return sequence.getEncoded(); } catch (IOException ex) { throw new CertificateEncodingException("Error encoding certificate path.", ex); } }
From source file:ca.trustpoint.m2m.M2mCertPath.java
License:Apache License
/** * Encode the CertPath using PKCS#7 format. * * @return a byte array containing the binary encoding of the PKCS#7 object * @exception CertificateEncodingException if an exception occurs */// ww w .j ava 2 s . co m private byte[] encodePkcs7() throws CertificateEncodingException { ASN1EncodableVector encodedList = new ASN1EncodableVector(); for (M2mCertificate certificate : certificates) { if (isDuplicateCertificate(certificate)) { throw new CertificateEncodingException("Duplicate certificate detected in path."); } try { encodedList.add(ASN1Primitive.fromByteArray(certificate.getEncoded())); } catch (IOException ex) { throw new CertificateEncodingException("Error encoding certificate data.", ex); } } SignedData sd = new SignedData(new ASN1Integer(BigInteger.ONE), // version new DERSet(), // digestAlgorithmIds new ContentInfo(PKCSObjectIdentifiers.data, null), // contentInfo new DERSet(encodedList), // certificates (optional) null, // CRLs (optional) new DERSet() // signerInfos ); // make it a content info sequence ContentInfo ci = new ContentInfo(PKCSObjectIdentifiers.data, sd); try { return ci.getEncoded(); } catch (IOException ex) { throw new CertificateEncodingException("Error encoding certificate path.", ex); } }
From source file:ch.bfh.unicert.certimport.CertificateIssuer.java
License:GNU General Public License
public Certificate createClientCertificate(IdentityData id, String keyStorePath, PublicKey pk, int validity, String applicationIdentifier, String[] roles, String uniBoardWsdlURL, String uniBoardServiceURL, String section) throws CertificateCreationException { X509Certificate caCert;/*from ww w.ja va 2 s . co m*/ RSAPrivateCrtKey privKey; try { caCert = this.readIssuerCertificate(this.issuerId); privKey = this.readPrivateKey(this.issuerId, this.privKeyPass); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) { logger.log(Level.SEVERE, null, ex); throw new CertificateCreationException("230 Could not create client certificate. Key error"); } RSAPrivateCrtKeyParameters cipherParams = this.createIssuerCipherParams(privKey); X509Certificate clientCert; Hashtable extension = new Hashtable(); extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier))); String completeRole = ""; for (String role : roles) { completeRole += role + ", "; } completeRole = completeRole.substring(0, completeRole.length() - 2); extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole))); extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider()))); Map<String, String> extensionMap = new HashMap(); if (id.getOtherValues() != null) { for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) { extension.put(new DERObjectIdentifier(entry.getKey().getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue()))); extensionMap.put(entry.getKey().getName(), entry.getValue()); } } try { String x509NameString = ""; x509NameString += "CN=" + id.getCommonName(); if (id.getSurname() != null && !id.getSurname().equals("")) { x509NameString += ", SURNAME=" + id.getSurname(); } if (id.getGivenName() != null && !id.getGivenName().equals("")) { x509NameString += ", GIVENNAME=" + id.getGivenName(); } if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) { x509NameString += ", UID=" + id.getUniqueIdentifier(); } if (id.getOrganisation() != null && !id.getOrganisation().equals("")) { x509NameString += ", O=" + id.getOrganisation(); } if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) { x509NameString += ", OU=" + id.getOrganisationUnit(); } if (id.getCountryName() != null && !id.getCountryName().equals("")) { x509NameString += ", C=" + id.getCountryName(); } if (id.getState() != null && !id.getState().equals("")) { x509NameString += ", ST=" + id.getState(); } if (id.getLocality() != null && !id.getLocality().equals("")) { x509NameString += ", L=" + id.getLocality(); } X509Name x509Name = new X509Name(x509NameString); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis()))); certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setSubject(x509Name); certGen.setExtensions(new X509Extensions(extension)); DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5"); AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull()); certGen.setSignature(sigAlgId); certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject())); certGen.setStartDate(new Time(new Date(System.currentTimeMillis()))); certGen.setEndDate(new Time(getExpiryDate(validity).getTime())); TBSCertificateStructure tbsCert = certGen.generateTBSCertificate(); //Sign certificate SHA1Digest digester = new SHA1Digest(); AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(tbsCert); byte[] signature; byte[] certBlock = bOut.toByteArray(); // first create digest digester.update(certBlock, 0, certBlock.length); byte[] hash = new byte[digester.getDigestSize()]; digester.doFinal(hash, 0); // then sign it rsa.init(true, cipherParams); DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash); byte[] digest = dInfo.getEncoded(ASN1Encodable.DER); signature = rsa.processBlock(digest, 0, digest.length); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgId); v.add(new DERBitString(signature)); // Create CRT data structure clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v))); clientCert.verify(caCert.getPublicKey()); } catch (IOException | InvalidCipherTextException | CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException e) { logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() }); throw new CertificateCreationException("230 Could not create client certificate"); } Certificate cert = new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap); //post message on UniBoard if corresponding JNDI parameter is defined postOnUniBoard(cert, uniBoardWsdlURL, uniBoardServiceURL, section, (RSAPublicKey) caCert.getPublicKey(), privKey); return cert; }
From source file:ch.bfh.unicert.issuer.CertificateIssuerBean.java
License:GNU General Public License
/** * Actually creates the requestor certificate. * * @param id requestor identity data/* w w w . j a va 2 s .c om*/ * @param caCert certificate of the certification authority * @param cipherParams issuer private key parameters used for signing * @param pk public key of the requestor to certify * @param expiry the expiry date * @param applicationIdentifier the application identifier for which te certificate is issued * @param role role for which the certificate is issued * @return the certificate object containing the X509 certificate * @throws CertificateCreationException if an error occurs */ private Certificate createClientCertificate(IdentityData id, X509Certificate caCert, CipherParameters cipherParams, PublicKey pk, Calendar expiry, String applicationIdentifier, String[] roles) throws CertificateCreationException { X509Certificate clientCert; Hashtable extension = new Hashtable(); extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier))); String completeRole = ""; for (String role : roles) { completeRole += role + ", "; } completeRole = completeRole.substring(0, completeRole.length() - 2); extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole))); extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider()))); Map<String, String> extensionMap = new HashMap(); if (id.getOtherValues() != null) { for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) { extension.put(new DERObjectIdentifier(entry.getKey().getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue()))); extensionMap.put(entry.getKey().getName(), entry.getValue()); } } try { String x509NameString = ""; x509NameString += "CN=" + id.getCommonName(); if (id.getSurname() != null && !id.getSurname().equals("")) { x509NameString += ", SURNAME=" + id.getSurname(); } if (id.getGivenName() != null && !id.getGivenName().equals("")) { x509NameString += ", GIVENNAME=" + id.getGivenName(); } if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) { x509NameString += ", UID=" + id.getUniqueIdentifier(); } if (id.getOrganisation() != null && !id.getOrganisation().equals("")) { x509NameString += ", O=" + id.getOrganisation(); } if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) { x509NameString += ", OU=" + id.getOrganisationUnit(); } if (id.getCountryName() != null && !id.getCountryName().equals("")) { x509NameString += ", C=" + id.getCountryName(); } if (id.getState() != null && !id.getState().equals("")) { x509NameString += ", ST=" + id.getState(); } if (id.getLocality() != null && !id.getLocality().equals("")) { x509NameString += ", L=" + id.getLocality(); } X509Name x509Name = new X509Name(x509NameString); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis()))); certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setSubject(x509Name); certGen.setExtensions(new X509Extensions(extension)); DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5"); AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull()); certGen.setSignature(sigAlgId); certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject())); certGen.setStartDate(new Time(new Date(System.currentTimeMillis()))); certGen.setEndDate(new Time(expiry.getTime())); TBSCertificateStructure tbsCert = certGen.generateTBSCertificate(); //Sign certificate SHA1Digest digester = new SHA1Digest(); AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(tbsCert); byte[] signature; byte[] certBlock = bOut.toByteArray(); // first create digest digester.update(certBlock, 0, certBlock.length); byte[] hash = new byte[digester.getDigestSize()]; digester.doFinal(hash, 0); // then sign it rsa.init(true, cipherParams); DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash); byte[] digest = dInfo.getEncoded(ASN1Encodable.DER); signature = rsa.processBlock(digest, 0, digest.length); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgId); v.add(new DERBitString(signature)); // Create CRT data structure clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v))); clientCert.verify(caCert.getPublicKey()); } catch (IOException | CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | InvalidCipherTextException | SignatureException e) { logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() }); throw new CertificateCreationException("230 Could not create client certificate"); } return new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap); }
From source file:chapter9.SignedMailExample.java
/** * * @param key//ww w.j a va 2s. c om * @param cert * @param certsAndCRLs * @param dataPart * @return * @throws Exception */ public static MimeMultipart createMultipartWithSignature(PrivateKey key, X509Certificate cert, CertStore certsAndCRLs, MimeBodyPart dataPart) throws Exception { //1.- Create some smime capabilities in case someone wants to respond ASN1EncodableVector signedAttrs = new ASN1EncodableVector(); SMIMECapabilityVector caps = new SMIMECapabilityVector(); caps.addCapability(SMIMECapability.aES256_CBC); caps.addCapability(SMIMECapability.dES_EDE3_CBC); caps.addCapability(SMIMECapability.rC2_CBC, 128); signedAttrs.add(new SMIMECapabilitiesAttribute(caps)); signedAttrs.add(new SMIMEEncryptionKeyPreferenceAttribute(SMIMEUtil.createIssuerAndSerialNumberFor(cert))); //2.- Set up the generator SMIMESignedGenerator gen = new SMIMESignedGenerator(); gen.addSigner(key, cert, SMIMESignedGenerator.DIGEST_SHA256, new AttributeTable(signedAttrs), null); gen.addCertificatesAndCRLs(certsAndCRLs); //3.- Create the signed message return gen.generate(dataPart, CryptoDefs.Provider.BC.getName()); }
From source file:com.aaasec.sigserv.cscommon.xmldsig.EcdsaSigValue.java
License:Open Source License
public DERSequence toASN1Object() { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DERInteger(r)); v.add(new DERInteger(s)); return new DERSequence(v); }
From source file:com.aaasec.sigserv.csspsupport.pdfbox.PdfBoxSigUtil.java
License:EUPL
/** * A method that updates the PDF PKCS7 object from the model object with a signature, * certificates and SignedAttributes obtains from an external source. The model contains * // w w w .ja v a2s . c o m * <p> * The PKCS7 Signed data found in the model can be created using a different * private key and certificate chain. This method effectively replace the signature * value and certificate with the replacement data obtained from the model. * * @param model A model for this signature replacement operation containing * necessary data for the process. * @return The bytes of an updated ODF signature PKCS7. */ public static byte[] updatePdfPKCS7(PdfSignModel model) { //New variables ByteArrayOutputStream bout = new ByteArrayOutputStream(); DEROutputStream dout = new DEROutputStream(bout); ASN1EncodableVector npkcs7 = new ASN1EncodableVector(); ASN1EncodableVector nsd = new ASN1EncodableVector(); ASN1EncodableVector nsi = new ASN1EncodableVector(); try { ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(model.getSignedData().getEncoded())); // // Basic checks to make sure it's a PKCS#7 SignedData Object // ASN1Primitive pkcs7; try { pkcs7 = din.readObject(); } catch (IOException e) { throw new IllegalArgumentException("Illegal PKCS7"); } if (!(pkcs7 instanceof ASN1Sequence)) { throw new IllegalArgumentException("Illegal PKCS7"); } ASN1Sequence signedData = (ASN1Sequence) pkcs7; ASN1ObjectIdentifier objId = (ASN1ObjectIdentifier) signedData.getObjectAt(0); if (!objId.getId().equals(PdfObjectIds.ID_PKCS7_SIGNED_DATA)) { throw new IllegalArgumentException("No SignedData"); } //Add Signed data content type to new PKCS7 npkcs7.add(objId); /** * SignedData ::= SEQUENCE { version CMSVersion, digestAlgorithms * DigestAlgorithmIdentifiers, encapContentInfo * EncapsulatedContentInfo, certificates [0] IMPLICIT CertificateSet * OPTIONAL, crls [1] IMPLICIT RevocationInfoChoices OPTIONAL, * signerInfos SignerInfos } */ //Get the SignedData sequence ASN1Sequence signedDataSeq = (ASN1Sequence) ((ASN1TaggedObject) signedData.getObjectAt(1)).getObject(); int sdObjCount = 0; // the version nsd.add(signedDataSeq.getObjectAt(sdObjCount++)); // the digestAlgorithms nsd.add(signedDataSeq.getObjectAt(sdObjCount++)); // the possible ecapsulated content info nsd.add(signedDataSeq.getObjectAt(sdObjCount++)); // the certificates. The certs are taken from the input parameters to the method //ASN1EncodableVector newCerts = new ASN1EncodableVector(); Certificate[] chain = model.getChain(); ASN1Encodable[] newCerts = new ASN1Encodable[chain.length]; //for (Certificate nCert : model.getCertChain()) { for (int i = 0; i < chain.length; i++) { ASN1InputStream cin = new ASN1InputStream(new ByteArrayInputStream(chain[i].getEncoded())); newCerts[i] = cin.readObject(); } nsd.add(new DERTaggedObject(false, 0, new DERSet(newCerts))); //Step counter past tagged objects while (signedDataSeq.getObjectAt(sdObjCount) instanceof ASN1TaggedObject) { ++sdObjCount; } //SignerInfos is the next object in the sequence of Signed Data (first untagged after certs) ASN1Set signerInfos = (ASN1Set) signedDataSeq.getObjectAt(sdObjCount); if (signerInfos.size() != 1) { throw new IllegalArgumentException("Unsupported multiple signer infos"); } ASN1Sequence signerInfo = (ASN1Sequence) signerInfos.getObjectAt(0); int siCounter = 0; // SignerInfo sequence // // 0 - CMSVersion // 1 - SignerIdentifier (CHOICE IssuerAndSerialNumber SEQUENCE) // 2 - DigestAglorithmIdentifier // 3 - [0] IMPLICIT SignedAttributes SET // 3 - Signature AlgorithmIdentifier // 4 - Signature Value OCTET STRING // 5 - [1] IMPLICIT UnsignedAttributes // //version nsi.add(signerInfo.getObjectAt(siCounter++)); // signing certificate issuer and serial number Certificate sigCert = chain[0]; ASN1EncodableVector issuerAndSerial = getIssuerAndSerial(sigCert); nsi.add(new DERSequence(issuerAndSerial)); siCounter++; //Digest AlgorithmIdentifier nsi.add(signerInfo.getObjectAt(siCounter++)); //Add signed attributes from signature service ASN1InputStream sigAttrIs = new ASN1InputStream(model.getCmsSigAttrBytes()); nsi.add(new DERTaggedObject(false, 0, sigAttrIs.readObject())); //Step counter past tagged objects (because signedAttrs i optional in the input data) while (signerInfo.getObjectAt(siCounter) instanceof ASN1TaggedObject) { siCounter++; } //Signature Alg identifier nsi.add(signerInfo.getObjectAt(siCounter++)); //Add new signature value from signing service nsi.add(new DEROctetString(model.getSignatureBytes())); siCounter++; //Add unsigned Attributes if present if (signerInfo.size() > siCounter && signerInfo.getObjectAt(siCounter) instanceof ASN1TaggedObject) { nsi.add(signerInfo.getObjectAt(siCounter)); } /* * Final Assembly */ // Add the SignerInfo sequence to the SignerInfos set and add this to the SignedData sequence nsd.add(new DERSet(new DERSequence(nsi))); // Add the SignedData sequence as a eplicitly tagged object to the pkcs7 object npkcs7.add(new DERTaggedObject(true, 0, new DERSequence(nsd))); dout.writeObject((new DERSequence(npkcs7))); byte[] pkcs7Bytes = bout.toByteArray(); dout.close(); bout.close(); return pkcs7Bytes; } catch (Exception e) { throw new IllegalArgumentException(e.toString()); } }
From source file:com.aaasec.sigserv.csspsupport.pdfbox.PdfBoxSigUtil.java
License:EUPL
/** * Internal helper method that constructs an IssuerAndSerial object for SignerInfo * based on a signer certificate.//w w w. j a v a 2 s .c o m * @param sigCert * @return An ASN1EncodableVector holding the IssuerAndSerial ASN.1 sequence. * @throws CertificateEncodingException * @throws IOException */ private static ASN1EncodableVector getIssuerAndSerial(Certificate sigCert) throws CertificateEncodingException, IOException { ASN1EncodableVector issuerAndSerial = new ASN1EncodableVector(); ASN1InputStream ain = new ASN1InputStream(sigCert.getEncoded()); ASN1Sequence certSeq = (ASN1Sequence) ain.readObject(); ASN1Sequence tbsSeq = (ASN1Sequence) certSeq.getObjectAt(0); int counter = 0; while (tbsSeq.getObjectAt(counter) instanceof ASN1TaggedObject) { counter++; } //Get serial ASN1Integer serial = (ASN1Integer) tbsSeq.getObjectAt(counter); counter += 2; ASN1Sequence issuerDn = (ASN1Sequence) tbsSeq.getObjectAt(counter); //Return the issuer field issuerAndSerial.add(issuerDn); issuerAndSerial.add(serial); return issuerAndSerial; }
From source file:com.android.verity.BootSignature.java
License:Apache License
public ASN1Object getAuthenticatedAttributes() { ASN1EncodableVector attrs = new ASN1EncodableVector(); attrs.add(target);//from w w w. j a va 2 s .co m attrs.add(length); return new DERSequence(attrs); }