List of usage examples for org.bouncycastle.asn1 ASN1Sequence size
public int size()
From source file:be.fedict.eid.pkira.crypto.csr.CSRInfo.java
License:Open Source License
public static <T> void getElementsFromASN1Sequence(ASN1Sequence sequence, ASN1ObjectIdentifier requiredObjectIdentifier, Class<T> expectedClass, List<T> resultList) { for (int j = 0; j < sequence.size(); j++) { DEREncodable object = sequence.getObjectAt(j); if (object instanceof DERSequence) { getElementsFromASN1Sequence((DERSequence) object, requiredObjectIdentifier, expectedClass, resultList);//from w ww. j a va 2 s . c o m } else { ASN1ObjectIdentifier objectIdentifier = (ASN1ObjectIdentifier) object; if (objectIdentifier.equals(requiredObjectIdentifier)) { resultList.add(expectedClass.cast(sequence.getObjectAt(j + 1))); } j++; } } }
From source file:ca.trustpoint.m2m.M2mCertificate.java
License:Apache License
/** * Converts this instance to its string representation using the given indentation level. * * @param depth Indentation level./* www. j av a 2s .c o m*/ * @return String representation of this instance at the given indentation level. */ public String toString(int depth) { StringBuffer buffer = new StringBuffer(); final String LINE_SEPARATOR = System.getProperty("line.separator"); FormattingUtils.indent(buffer, depth).append("M2MCertificate [APPLICATION 20] SEQUENCE {") .append(LINE_SEPARATOR); FormattingUtils.indent(buffer, depth + 1).append("[0] tbsCertificate TBSCertificate: ") .append(LINE_SEPARATOR); FormattingUtils.indent(buffer, depth + 2).append("TBSCertificate SEQUENCE {").append(LINE_SEPARATOR); FormattingUtils.indent(buffer, depth + 3).append("[ 0] version INTEGER: "); buffer.append(VERSION).append(LINE_SEPARATOR); if (serialNumber != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 1] serialNumber OCTET STRING: "); buffer.append(Hex.toHexString(serialNumber)).append(LINE_SEPARATOR); } if (caKeyDefinition != null) { if (caKeyDefinition.getAlgorithm() != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 2] cAAlgorithm OBJECT IDENTIFIER: "); buffer.append(caKeyDefinition.getAlgorithm().getOid()).append(LINE_SEPARATOR); } if (caKeyDefinition.getParameters() != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 3] cAAlgParams OCTET STRING: "); buffer.append(Hex.toHexString(caKeyDefinition.getParameters())).append(LINE_SEPARATOR); } } if (issuer != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 4] issuer Name: ").append(LINE_SEPARATOR); buffer.append(issuer.toString(depth + 4)); } if (validFrom != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 5] validFrom OCTET STRING: "); buffer.append(Hex.toHexString(BigInteger.valueOf(validFrom.getTime() / 1000).toByteArray())) .append(LINE_SEPARATOR); } if (validDuration != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 6] validDuration OCTET STRING: "); buffer.append(validDuration).append(LINE_SEPARATOR); } if (subject != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 7] subject Name: ").append(LINE_SEPARATOR); buffer.append(subject.toString(depth + 4)); } if (publicKeyDefinition != null) { if (publicKeyDefinition.getAlgorithm() != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 8] pKAlgorithm OBJECT IDENTIFIER: "); buffer.append(publicKeyDefinition.getAlgorithm()).append(LINE_SEPARATOR); } if (publicKeyDefinition.getParameters() != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 9] pKAlgParams OCTET STRING: "); buffer.append(Hex.toHexString(publicKeyDefinition.getParameters())).append(LINE_SEPARATOR); } } if (publicKey != null) { FormattingUtils.indent(buffer, depth + 3).append("[10] pubKey OCTET STRING: "); buffer.append(Hex.toHexString(publicKey.getEncoded())).append(LINE_SEPARATOR); } if (authorityKeyIdentifier != null) { FormattingUtils.indent(buffer, depth + 3).append("[11] authKeyId OCTET STRING: ") .append(LINE_SEPARATOR); buffer.append(authorityKeyIdentifier.toString(depth + 4)).append(LINE_SEPARATOR); } if (subjectKeyIdentifier != null) { FormattingUtils.indent(buffer, depth + 3).append("[12] subjKeyId OCTET STRING: "); buffer.append(Hex.toHexString(subjectKeyIdentifier)).append(LINE_SEPARATOR); } if (keyUsage != null) { FormattingUtils.indent(buffer, depth + 3).append("[13] keyUsage OCTET STRING: "); buffer.append(keyUsage.toString(depth + 4)).append(LINE_SEPARATOR); } if (basicConstraints != null) { FormattingUtils.indent(buffer, depth + 3).append("[14] basicConstraints INTEGER: "); buffer.append(basicConstraints).append(LINE_SEPARATOR); } if (certificatePolicy != null) { FormattingUtils.indent(buffer, depth + 3).append("[15] certificatePolicy OBJECT IDENTIFIER: "); buffer.append(certificatePolicy).append(LINE_SEPARATOR); } if (subjectAlternativeName != null) { FormattingUtils.indent(buffer, depth + 3).append("[16] subjectAltName GeneralName: "); buffer.append(subjectAlternativeName.toString(depth + 4)).append(LINE_SEPARATOR); } if (issuerAlternativeName != null) { FormattingUtils.indent(buffer, depth + 3).append("[17] issuerAltName GeneralName: "); buffer.append(issuerAlternativeName.toString(depth + 4)).append(LINE_SEPARATOR); } if (extendedKeyUsage != null) { FormattingUtils.indent(buffer, depth + 3).append("[18] extendedKeyUsage OBJECT IDENTIFIER: "); buffer.append(extendedKeyUsage).append(LINE_SEPARATOR); } if (authenticationInfoAccessOcsp != null) { FormattingUtils.indent(buffer, depth + 3).append("[19] authInfoAccess IA5String: "); buffer.append(authenticationInfoAccessOcsp.toString()).append(LINE_SEPARATOR); } if (crlDistributionPointUri != null) { FormattingUtils.indent(buffer, depth + 3).append("[20] cRLDistribPoint IA5String: "); buffer.append(crlDistributionPointUri.toString()).append(LINE_SEPARATOR); } if (!extensions.isEmpty()) { FormattingUtils.indent(buffer, depth + 3).append("[21] x509extensions:").append(LINE_SEPARATOR); FormattingUtils.indent(buffer, depth + 4).append("X509Extensions SEQUENCE {").append(LINE_SEPARATOR); for (int i = 0; i < extensions.size(); i++) { Extension e = extensions.get(i); FormattingUtils.indent(buffer, depth + 5).append("[").append(i).append("] Extension SEQUENCE {") .append(LINE_SEPARATOR); FormattingUtils.indent(buffer, depth + 6).append("extnId OBJECT IDENTIFIER: "); buffer.append(e.oid).append(LINE_SEPARATOR); FormattingUtils.indent(buffer, depth + 6).append("criticality BOOLEAN: "); buffer.append((e.isCritical ? "TRUE" : "FALSE")).append(LINE_SEPARATOR); if (e.value != null) { FormattingUtils.indent(buffer, depth + 6).append("extnValue OCTET STRING: "); buffer.append(Hex.toHexString(e.value)).append(LINE_SEPARATOR); } FormattingUtils.indent(buffer, depth + 5).append("}").append(LINE_SEPARATOR); } FormattingUtils.indent(buffer, depth + 4).append("}").append(LINE_SEPARATOR); } if (caCalcValue != null) { ASN1Sequence caCalcValueSequence = null; // The caCalcValue is an ASN1Sequence for non-ECQV certificate but not for ECQV // certificate, so exception may be encountered try { caCalcValueSequence = ASN1Sequence.getInstance(caCalcValue); } catch (Exception e) { // Not an ASN1Sequence caCalcValueSequence = null; } if (caCalcValueSequence != null) { FormattingUtils.indent(buffer, depth + 1).append("[1] cACalcValue OCTET STRING representing: ") .append(LINE_SEPARATOR); FormattingUtils.indent(buffer, depth + 2).append("SEQUENCE {").append(LINE_SEPARATOR); for (int i = 0; i < caCalcValueSequence.size(); i++) { try { FormattingUtils.indent(buffer, depth + 3).append("INTEGER: ") .append(Hex.toHexString( caCalcValueSequence.getObjectAt(i).toASN1Primitive().getEncoded())) .append(LINE_SEPARATOR); } catch (IOException ex) { // Do nothing. } } FormattingUtils.indent(buffer, depth + 2).append("}").append(LINE_SEPARATOR); } else { FormattingUtils.indent(buffer, depth + 1).append("[1] cACalcValue OCTET STRING: "); buffer.append(Hex.toHexString(caCalcValue)).append(LINE_SEPARATOR); } } FormattingUtils.indent(buffer, depth).append("}").append(LINE_SEPARATOR); return buffer.toString(); }
From source file:ca.trustpoint.m2m.M2mCertificateFactory.java
License:Apache License
/** * Generates a certificate object and initializes it with the data read from the * {@link java.io.InputStream InputStream} {@code inStream}. * * <p>/* w ww .j a v a 2 s .c om*/ * The returned certificate object can be casted to the {@link M2mCertificate M2MCertificate} * class. * * <p> * The certificate provided in {@code inStream} must be DER-encoded and may be supplied in binary * or printable (Base64) encoding. If the certificate is provided in Base64 encoding, it must be * bounded at the beginning by -----BEGIN CERTIFICATE-----, and must be bounded at the end by * -----END CERTIFICATE-----. * * <p> * Note that if the given input stream does not support {@link java.io.InputStream#mark(int) mark} * and {@link java.io.InputStream#reset() reset}, this method will consume the entire input * stream. Otherwise, each call to this method consumes one certificate and the read position of * the input stream is positioned to the next available byte after the inherent end-of-certificate * marker. If the data in the input stream does not contain an inherent end-of-certificate marker * (other than EOF) and there is trailing data after the certificate is parsed, a * {@link java.security.cert.CertificateException CertificateException} is thrown. * * @param inStream an input stream with the certificate data. * * @return a certificate object initialized with the data from the input stream. * * @exception CertificateException on parsing errors. */ @Override public Certificate engineGenerateCertificate(InputStream inStream) throws CertificateException { if (inStream == null) { throw new IllegalArgumentException("input stream is null"); } try { ASN1InputStream aIn = new ASN1InputStream(inStream); ASN1ApplicationSpecific app = ASN1ApplicationSpecific.getInstance(aIn.readObject()); aIn.close(); int appTag = app.getApplicationTag(); if (appTag != M2mCertificate.APPLICATION_TAG_NUMBER) { throw new IOException("not M2M certificate application tag: " + appTag); } ASN1Sequence seq = (ASN1Sequence) app.getObject(BERTags.SEQUENCE); if (seq.size() != 2) { throw new IOException("sequence wrong size for a M2M certificate"); } // Construct M2M certificate M2mCertificate cert = new M2mCertificate(); for (int i = 0; i < seq.size(); i++) { ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(i); CertificateFields tag = CertificateFields.getInstance(obj.getTagNo()); switch (tag) { case TBS_CERTIFICATE: ASN1Sequence tbsCertificate = ASN1Sequence.getInstance(obj, false); parseTbsCertificate(tbsCertificate, cert); break; case CA_CALC_VALUE: ASN1OctetString cACalcValue = ASN1OctetString.getInstance(obj, false); cert.setCaCalcValue(cACalcValue.getOctets()); break; default: throw new IOException("unknown M2M data field number: " + tag.getTagNumber()); } } return cert; } catch (Exception e) { // Catch all exceptions and convert it to a CertificateException throw new CertificateException("exception on parsing certificate data", e); } }
From source file:ca.trustpoint.m2m.M2mCertificateFactory.java
License:Apache License
/** * Parses the given ASN.1 sequence and return the corresponding {@link M2mCertificate * M2MCertificate} object./*from w ww .j a v a 2 s . c o m*/ * * @param seq ASN.1 sequence containing TBS data. * @param cert A M2MCertificate object. * @throw InvalidKeyException if public key is invalid. * @throw IOException if parsing error. * @throw URISyntaxException if URI field is invalid. */ private void parseTbsCertificate(ASN1Sequence seq, M2mCertificate cert) throws InvalidKeyException, IOException, URISyntaxException { if (seq.size() < 2) { throw new IOException("no enough data for TBS certificate in sequence"); } // Set tbsCertificate for (int i = 0; i < seq.size(); i++) { ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(i); TbsCertificateFields tag = TbsCertificateFields.getInstance(obj.getTagNo()); switch (tag) { case SERIAL_NUMBER: ASN1OctetString serialNumber = ASN1OctetString.getInstance(obj, false); cert.setSerialNumber(serialNumber.getOctets()); break; case CA_ALGORITHM: ASN1ObjectIdentifier cAAlgorithm = ASN1ObjectIdentifier.getInstance(obj, false); if (cert.getCaKeyDefinition() == null) { cert.setCaKeyDefinition(new KeyAlgorithmDefinition()); } cert.getCaKeyDefinition().setAlgorithm(parseKeyAlgorithmDefinitionAlgorithm(cAAlgorithm)); break; case CA_ALGORITHM_PARAMETERS: ASN1OctetString cAAlgParams = ASN1OctetString.getInstance(obj, false); if (cert.getCaKeyDefinition() == null) { cert.setCaKeyDefinition(new KeyAlgorithmDefinition()); } cert.getCaKeyDefinition().setParameters(cAAlgParams.getOctets()); break; case ISSUER: ASN1Sequence issuerSeq = ASN1Sequence.getInstance(obj, false); cert.setIssuer(parseEntityName(issuerSeq)); break; case VALID_FROM: ASN1OctetString validFrom = ASN1OctetString.getInstance(obj, false); BigInteger dateTimeBInt = new BigInteger(validFrom.getOctets()); // date in sequence is second, converts to millisecond for constructing Date long dateTime = dateTimeBInt.longValue() * 1000; cert.setValidFrom(new Date(dateTime)); break; case VALID_DURATION: ASN1OctetString validDuration = ASN1OctetString.getInstance(obj, false); BigInteger duration = new BigInteger(validDuration.getOctets()); cert.setValidDuration(new Integer(duration.intValue())); break; case SUBJECT: ASN1Sequence subjectSeq = ASN1Sequence.getInstance(obj, false); cert.setSubject(parseEntityName(subjectSeq)); break; case PUBLIC_KEY_ALGORITHM: ASN1ObjectIdentifier pKAlgorithm = ASN1ObjectIdentifier.getInstance(obj, false); if (cert.getPublicKeyDefinition() == null) { cert.setPublicKeyDefinition(new KeyAlgorithmDefinition()); } cert.getPublicKeyDefinition().setAlgorithm(parseKeyAlgorithmDefinitionAlgorithm(pKAlgorithm)); break; case PUBLIC_KEY_ALGORITHM_PARAMETERS: ASN1OctetString pKAlgParams = ASN1OctetString.getInstance(obj, false); if (cert.getPublicKeyDefinition() == null) { cert.setPublicKeyDefinition(new KeyAlgorithmDefinition()); } cert.getPublicKeyDefinition().setParameters(pKAlgParams.getOctets()); break; case PUBLIC_KEY: ASN1OctetString pubKey = ASN1OctetString.getInstance(obj, false); byte[] rawPublicKey = pubKey.getOctets(); cert.setIsPublicKeyCompressed(KeyConversionUtils.isCompressedEcPoint(rawPublicKey)); PublicKey publicKey = KeyConversionUtils.convertRawBytestoEcPublicKey(rawPublicKey); cert.setPublicKey(publicKey); break; case AUTHORITY_KEY_ID: ASN1Sequence authKeyIdSeq = ASN1Sequence.getInstance(obj, false); cert.setAuthorityKeyIdentifier(parseAuthorityKeyIdentifier(authKeyIdSeq)); break; case SUBJECT_KEY_ID: ASN1OctetString subjKeyId = ASN1OctetString.getInstance(obj, false); cert.setSubjectKeyIdentifier(subjKeyId.getOctets()); break; case KEY_USAGE: ASN1OctetString keyUsageObj = ASN1OctetString.getInstance(obj, false); KeyUsage keyUsage = new KeyUsage(keyUsageObj.getEncoded()); cert.setKeyUsage(keyUsage); break; case BASIC_CONSTRAINTS: ASN1Integer basicConstraints = ASN1Integer.getInstance(obj, false); cert.setBasicConstraints(basicConstraints.getValue().intValue()); break; case CERTIFICATE_POLICY: ASN1ObjectIdentifier certPolicy = ASN1ObjectIdentifier.getInstance(obj, false); cert.setCertificatePolicy(certPolicy.getId()); break; case SUBJECT_ALTERNATE_NAME: ASN1TaggedObject subjectAltNameObj = ASN1TaggedObject.getInstance(obj, true); cert.setSubjectAlternativeName(parseGeneralName(subjectAltNameObj)); break; case ISSUER_ALTERNATE_NAME: ASN1TaggedObject issuerAltNameObj = ASN1TaggedObject.getInstance(obj, true); cert.setIssuerAlternativeName(parseGeneralName(issuerAltNameObj)); break; case EXTENDED_KEY_USAGE: ASN1ObjectIdentifier extendedKeyUsage = ASN1ObjectIdentifier.getInstance(obj, false); cert.setExtendedKeyUsage(extendedKeyUsage.getId()); break; case AUTHENTICATION_INFO_ACCESS_OCSP: DERIA5String authInfoAccessOCSPObj = DERIA5String.getInstance(obj, false); URI authInfoAccessOCSP = new URI(authInfoAccessOCSPObj.getString()); cert.setAuthenticationInfoAccessOcsp(authInfoAccessOCSP); break; case CRL_DISTRIBUTION_POINT_URI: DERIA5String cRLDistribPointURIObj = DERIA5String.getInstance(obj, false); URI cRLDistribPointURI = new URI(cRLDistribPointURIObj.getString()); cert.setCrlDistributionPointUri(cRLDistribPointURI); break; case EXTENSIONS: ASN1Sequence x509extensionsSeq = ASN1Sequence.getInstance(obj, false); parseX509extensions(x509extensionsSeq, cert); break; default: throw new IOException("unknow TBS certificate field number: " + tag.getTagNumber()); } } }
From source file:ca.trustpoint.m2m.M2mCertificateFactory.java
License:Apache License
/** * Parses ASN.1 sequence to construct an {@link EntityName} object. * * @param seq ASN.1 sequence data for {@link EntityName}. * @return An instance of {@link EntityName} constructed from seq. * @throw IOException if parsing has error or not enough data or too much data *//*from w ww .ja v a 2 s.c o m*/ private EntityName parseEntityName(ASN1Sequence seq) throws IOException { if (seq.size() < EntityName.MINIMUM_ATTRIBUTES) { throw new IOException("no name attribute in sequence"); } else if (seq.size() > EntityName.MAXIMUM_ATTRIBUTES) { throw new IOException("too many name attributes in sequence:" + seq.size()); } EntityName name = new EntityName(); for (int i = 0; i < seq.size(); i++) { ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(i); name.addAttribute(parseEntityNameAttribute(obj)); } return name; }
From source file:ca.trustpoint.m2m.M2mCertificateFactory.java
License:Apache License
/** * Parses ASN.1 sequence to construct an {@link AuthorityKeyIdentifier} object. * * @param seq An ASN.1 sequence.// w w w . java 2 s . co m * @return An instance of {@link AuthorityKeyIdentifier} constructed from seq. * @throw IOException if parsing error or data invalid. */ private AuthorityKeyIdentifier parseAuthorityKeyIdentifier(ASN1Sequence seq) throws IOException { if (seq.size() < 1) { throw new IOException("no authKeyId data in sequence"); } else if (seq.size() > 3) { throw new IOException("too much authKeyId data in sequence: " + seq.size()); } AuthorityKeyIdentifier authKeyId = new AuthorityKeyIdentifier(); for (int i = 0; i < seq.size(); i++) { ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(i); switch (obj.getTagNo()) { case AuthorityKeyIdentifier.INDEX_KEY_IDENTIFIER: ASN1OctetString identifierObj = ASN1OctetString.getInstance(obj, false); authKeyId.setKeyIdentifier(identifierObj.getOctets()); break; case AuthorityKeyIdentifier.INDEX_AUTH_CERT_ISSUER: ASN1TaggedObject authCertIssuerObj = ASN1TaggedObject.getInstance(obj, true); authKeyId.setCertificateIssuer(parseGeneralName(authCertIssuerObj)); break; case AuthorityKeyIdentifier.INDEX_AUTH_CERT_SERIAL_NUM: ASN1OctetString authCertSerialNumObj = ASN1OctetString.getInstance(obj, false); BigInteger serialNumber = new BigInteger(authCertSerialNumObj.getOctets()); authKeyId.setCertificateSerialNumber(serialNumber); break; default: throw new IOException("unknown authKeyId index: " + obj.getTagNo()); } } if (!authKeyId.isValid()) { throw new IOException("invalid AuthorityKeyIdentifier instance parsed from ASN.1 sequence"); } return authKeyId; }
From source file:ca.trustpoint.m2m.M2mCertificateFactory.java
License:Apache License
/** * Parses ASN.1 sequence to set up X.509 extentions of a {@link M2mCertificate} object. * * @param seq An ASN.1 sequence containing X.509 extentions. * @param cert A {@link M2mCertificate} object to be filled. * @throw IOException if parsing error or data invalid. *///w w w . ja v a 2s. c o m private void parseX509extensions(ASN1Sequence seq, M2mCertificate cert) throws IOException { if (seq.size() < 1) { throw new IOException("not X.509 extension data in sequence"); } for (int i = 0; i < seq.size(); i++) { ASN1Sequence extSeq = (ASN1Sequence) seq.getObjectAt(i); if (extSeq.size() < 2) { throw new IOException("no enough data fields for X.509 extension in sequence"); } else if (extSeq.size() > 3) { throw new IOException("too many data fields for X.509 extension in sequence"); } String oid = null; boolean isCritical = false; byte[] value = null; for (int j = 0; j < extSeq.size(); j++) { ASN1TaggedObject obj = (ASN1TaggedObject) extSeq.getObjectAt(j); switch (obj.getTagNo()) { case 0: // oid ASN1ObjectIdentifier oidObj = ASN1ObjectIdentifier.getInstance(obj, false); oid = oidObj.getId(); break; case 1: // isCritical ASN1Boolean isCriticalObj = ASN1Boolean.getInstance(obj, false); isCritical = isCriticalObj.isTrue(); break; case 2: // value ASN1OctetString valueObj = ASN1OctetString.getInstance(obj, false); value = valueObj.getOctets(); break; default: throw new IOException("unknown x509extension ID: " + obj.getTagNo()); } } cert.addExtension(oid, isCritical, value); } }
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 * //from w w w .jav a 2 s . c om * <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.goodvikings.cryptim.api.KeyRing.java
License:BEER-WARE LICENSE
private void ASN1DecodeKeys(byte[] plain) throws IOException, PGPException, NoSuchProviderException, ParseException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException { JcaPGPKeyConverter converter = new JcaPGPKeyConverter(); ASN1Sequence seq = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(plain)).readObject(); PGPPublicKey pub = converter.getPGPPublicKey(PGPPublicKey.RSA_GENERAL, new RSAPublicKeyImpl( ((ASN1OctetString) ((ASN1Sequence) seq.getObjectAt(0)).getObjectAt(1)).getOctets()), ((ASN1UTCTime) ((ASN1Sequence) seq.getObjectAt(0)).getObjectAt(0)).getAdjustedDate()); kp = new PGPKeyPair(pub, converter.getPGPPrivateKey(pub, KeyFactory.getInstance("RSA") .generatePrivate(new PKCS8EncodedKeySpec(((ASN1OctetString) seq.getObjectAt(1)).getOctets())))); ASN1Sequence keySeq = (ASN1Sequence) seq.getObjectAt(2); for (int i = 0; i < keySeq.size(); i++) { keys.put(((DERUTF8String) ((ASN1Sequence) keySeq.getObjectAt(i)).getObjectAt(0)).getString(), converter.getPGPPublicKey(PGPPublicKey.RSA_GENERAL, new RSAPublicKeyImpl( ((ASN1OctetString) ((ASN1Sequence) keySeq.getObjectAt(i)).getObjectAt(3)).getOctets()), ((ASN1UTCTime) ((ASN1Sequence) keySeq.getObjectAt(i)).getObjectAt(2)) .getAdjustedDate())); nicks.put(((DERUTF8String) ((ASN1Sequence) keySeq.getObjectAt(i)).getObjectAt(0)).getString(), ((DERUTF8String) ((ASN1Sequence) keySeq.getObjectAt(i)).getObjectAt(1)).getString()); }// w ww .j a v a2 s . c om }
From source file:com.itextpdf.signatures.CertificateUtil.java
License:Open Source License
/** * Retrieves the OCSP URL from the given certificate. * @param certificate the certificate//from ww w.java 2 s.co m * @return the URL or null * @throws IOException */ public static String getOCSPURL(X509Certificate certificate) { ASN1Primitive obj; try { obj = getExtensionValue(certificate, Extension.authorityInfoAccess.getId()); if (obj == null) { return null; } ASN1Sequence AccessDescriptions = (ASN1Sequence) obj; for (int i = 0; i < AccessDescriptions.size(); i++) { ASN1Sequence AccessDescription = (ASN1Sequence) AccessDescriptions.getObjectAt(i); if (AccessDescription.size() != 2) { continue; } else if (AccessDescription.getObjectAt(0) instanceof ASN1ObjectIdentifier) { ASN1ObjectIdentifier id = (ASN1ObjectIdentifier) AccessDescription.getObjectAt(0); if (SecurityIDs.ID_OCSP.equals(id.getId())) { ASN1Primitive description = (ASN1Primitive) AccessDescription.getObjectAt(1); String AccessLocation = getStringFromGeneralName(description); if (AccessLocation == null) { return ""; } else { return AccessLocation; } } } } } catch (IOException e) { return null; } return null; }