List of usage examples for org.bouncycastle.asn1 DERObjectIdentifier getId
public String getId()
From source file:br.gov.frameworkdemoiselle.certificate.oid.OIDGeneric.java
License:Open Source License
/** * Instance for object./*from w w w. j a v a 2s. c o m*/ * * @param data -> byte array with certificate content. * @return Object GenericOID * @throws IOException * @throws Exception */ public static OIDGeneric getInstance(byte[] data) throws IOException, Exception { ASN1InputStream is = new ASN1InputStream(data); DERSequence sequence = (DERSequence) is.readObject(); DERObjectIdentifier objectIdentifier = (DERObjectIdentifier) sequence.getObjectAt(0); DERTaggedObject tag = (DERTaggedObject) sequence.getObjectAt(1); DEROctetString octetString = null; DERPrintableString printableString = null; DERUTF8String utf8String = null; DERIA5String ia5String = null; try { octetString = (DEROctetString) DEROctetString.getInstance(tag); } catch (Exception ex) { try { printableString = DERPrintableString.getInstance(tag); } catch (Exception e1) { try { utf8String = DERUTF8String.getInstance(tag); } catch (Exception e2) { ia5String = DERIA5String.getInstance(tag); } } } String className = "br.gov.frameworkdemoiselle.certificate.oid.OID_" + objectIdentifier.getId().replaceAll("[.]", "_"); OIDGeneric oidGenerico; try { oidGenerico = (OIDGeneric) Class.forName(className).newInstance(); } catch (InstantiationException e) { throw new Exception("Can not instace class '" + className + "'.", e); } catch (IllegalAccessException e) { throw new Exception("Was not possible instace class '" + className + "'.", e); } catch (ClassNotFoundException e) { oidGenerico = new OIDGeneric(); } oidGenerico.setOid(objectIdentifier.getId()); if (octetString != null) { oidGenerico.setData(new String(octetString.getOctets())); } else if (printableString != null) { oidGenerico.setData(printableString.getString()); } else if (utf8String != null) { oidGenerico.setData(utf8String.getString()); } else { oidGenerico.setData(ia5String.getString()); } oidGenerico.initialize(); return oidGenerico; }
From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.CAdESSigner.java
License:Open Source License
/** * A validao se basea apenas em assinaturas com um assinante apenas. * Valida apenas com o contedo do tipo DATA: OID ContentType * 1.2.840.113549.1.9.3 = OID Data 1.2.840.113549.1.7.1 * * @param content/* w w w . ja v a 2 s . c om*/ * @param signed * @return * @params content Necessrio informar apenas se o pacote PKCS7 NO for do * tipo ATTACHED. Caso seja do tipo attached, este parmetro ser * substituido pelo contedo do pacote PKCS7. * @params signed Valor em bytes do pacote PKCS7, como por exemplo o * contedo de um arquivo ".p7s". No a assinatura pura como no caso do * PKCS1. TODO: Implementar validao de co-assinaturas */ @Override public boolean check(byte[] content, byte[] signed) { CMSSignedData signedData = null; PublicKey publicKey = null; try { if (content == null) { signedData = new CMSSignedData(signed); } else { signedData = new CMSSignedData(new CMSProcessableByteArray(content), signed); } } catch (CMSException exception) { throw new SignerException("Invalid bytes for a PKCS7 package", exception); } SignerInformationStore signerInformationStore = signedData.getSignerInfos(); SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator() .next(); /* * Retirando o Certificado Digital e a chave Pblica da assinatura */ try { CertStore certs; try { Security.addProvider(new BouncyCastleProvider()); certs = signedData.getCertificatesAndCRLs("Collection", "BC"); Collection<? extends Certificate> collCertificados = certs .getCertificates(signerInformation.getSID()); if (!collCertificados.isEmpty()) { certificate = (X509Certificate) collCertificados.iterator().next(); publicKey = certificate.getPublicKey(); } } catch (NoSuchAlgorithmException exception) { throw new SignerException(exception); } catch (NoSuchProviderException exception) { throw new SignerException(exception); } catch (CMSException exception) { throw new SignerException(exception); } catch (CertStoreException exception) { throw new SignerException(exception); } } catch (SignerException ex) { throw new SignerException( "Error on get information about certificates and public keys from a package PKCS7", ex); } try { signerInformation.verify(publicKey, "BC"); } catch (NoSuchAlgorithmException e) { throw new SignerException(e); } catch (NoSuchProviderException e) { throw new SignerException(e); } catch (CMSException e) { throw new SignerException("Invalid signature", e); } AttributeTable signedAttributes = signerInformation.getSignedAttributes(); if (signedAttributes == null) { throw new SignerException("Package PKCS7 without signed attributes"); } // Validar a poltica org.bouncycastle.asn1.cms.Attribute signaturePolicyIdentifierAttribute = signedAttributes .get(new DERObjectIdentifier((new SignaturePolicyIdentifier()).getOID())); if (signaturePolicyIdentifierAttribute != null) { ASN1Set valueAttribute = signaturePolicyIdentifierAttribute.getAttrValues(); for (Enumeration<DERSequence> iterator = valueAttribute.getObjects(); iterator.hasMoreElements();) { DERSequence sequence = iterator.nextElement(); DERObjectIdentifier policyIdentifier = (DERObjectIdentifier) sequence.getObjectAt(0); String policyOID = policyIdentifier.getId(); SignaturePolicy policy = SignaturePolicyFactory.getInstance().factory(policyOID); if (policy != null) { policy.validate(content, signed); } else { LOGGER.log(Level.WARNING, "N\u00e3o existe validador para a pol\u00edtica {0}", policyOID); } } } else { throw new SignerException("ICP-Brasil invalid format. There is not policy signature."); } return true; }
From source file:com.itextpdf.text.pdf.PdfPKCS7.java
License:Open Source License
/** * Verifies a signature using the sub-filter adbe.pkcs7.detached or * adbe.pkcs7.sha1./* www. j ava2 s . c o m*/ * @param contentsKey the /Contents key * @param provider the provider or <code>null</code> for the default provider */ @SuppressWarnings("unchecked") public PdfPKCS7(byte[] contentsKey, String provider) { try { this.provider = provider; ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(contentsKey)); // // Basic checks to make sure it's a PKCS#7 SignedData Object // DERObject pkcs; try { pkcs = din.readObject(); } catch (IOException e) { throw new IllegalArgumentException( MessageLocalization.getComposedMessage("can.t.decode.pkcs7signeddata.object")); } if (!(pkcs instanceof ASN1Sequence)) { throw new IllegalArgumentException( MessageLocalization.getComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence")); } ASN1Sequence signedData = (ASN1Sequence) pkcs; DERObjectIdentifier objId = (DERObjectIdentifier) signedData.getObjectAt(0); if (!objId.getId().equals(ID_PKCS7_SIGNED_DATA)) throw new IllegalArgumentException( MessageLocalization.getComposedMessage("not.a.valid.pkcs.7.object.not.signed.data")); ASN1Sequence content = (ASN1Sequence) ((DERTaggedObject) signedData.getObjectAt(1)).getObject(); // the positions that we care are: // 0 - version // 1 - digestAlgorithms // 2 - possible ID_PKCS7_DATA // (the certificates and crls are taken out by other means) // last - signerInfos // the version version = ((DERInteger) content.getObjectAt(0)).getValue().intValue(); // the digestAlgorithms digestalgos = new HashSet<String>(); Enumeration<ASN1Sequence> e = ((ASN1Set) content.getObjectAt(1)).getObjects(); while (e.hasMoreElements()) { ASN1Sequence s = e.nextElement(); DERObjectIdentifier o = (DERObjectIdentifier) s.getObjectAt(0); digestalgos.add(o.getId()); } // the certificates X509CertParser cr = new X509CertParser(); cr.engineInit(new ByteArrayInputStream(contentsKey)); certs = cr.engineReadAll(); // the possible ID_PKCS7_DATA ASN1Sequence rsaData = (ASN1Sequence) content.getObjectAt(2); if (rsaData.size() > 1) { DEROctetString rsaDataContent = (DEROctetString) ((DERTaggedObject) rsaData.getObjectAt(1)) .getObject(); RSAdata = rsaDataContent.getOctets(); } // the signerInfos int next = 3; while (content.getObjectAt(next) instanceof DERTaggedObject) ++next; ASN1Set signerInfos = (ASN1Set) content.getObjectAt(next); if (signerInfos.size() != 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage( "this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time")); ASN1Sequence signerInfo = (ASN1Sequence) signerInfos.getObjectAt(0); // the positions that we care are // 0 - version // 1 - the signing certificate issuer and serial number // 2 - the digest algorithm // 3 or 4 - digestEncryptionAlgorithm // 4 or 5 - encryptedDigest signerversion = ((DERInteger) signerInfo.getObjectAt(0)).getValue().intValue(); // Get the signing certificate ASN1Sequence issuerAndSerialNumber = (ASN1Sequence) signerInfo.getObjectAt(1); X509Principal issuer = new X509Principal( issuerAndSerialNumber.getObjectAt(0).getDERObject().getEncoded()); BigInteger serialNumber = ((DERInteger) issuerAndSerialNumber.getObjectAt(1)).getValue(); for (Object element : certs) { X509Certificate cert = (X509Certificate) element; if (issuer.equals(cert.getIssuerDN()) && serialNumber.equals(cert.getSerialNumber())) { signCert = cert; break; } } if (signCert == null) { throw new IllegalArgumentException( MessageLocalization.getComposedMessage("can.t.find.signing.certificate.with.serial.1", issuer.getName() + " / " + serialNumber.toString(16))); } signCertificateChain(); digestAlgorithm = ((DERObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(2)).getObjectAt(0)) .getId(); next = 3; if (signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) { ASN1TaggedObject tagsig = (ASN1TaggedObject) signerInfo.getObjectAt(next); ASN1Set sseq = ASN1Set.getInstance(tagsig, false); sigAttr = sseq.getEncoded(ASN1Encodable.DER); for (int k = 0; k < sseq.size(); ++k) { ASN1Sequence seq2 = (ASN1Sequence) sseq.getObjectAt(k); if (((DERObjectIdentifier) seq2.getObjectAt(0)).getId().equals(ID_MESSAGE_DIGEST)) { ASN1Set set = (ASN1Set) seq2.getObjectAt(1); digestAttr = ((DEROctetString) set.getObjectAt(0)).getOctets(); } else if (((DERObjectIdentifier) seq2.getObjectAt(0)).getId().equals(ID_ADBE_REVOCATION)) { ASN1Set setout = (ASN1Set) seq2.getObjectAt(1); ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0); for (int j = 0; j < seqout.size(); ++j) { ASN1TaggedObject tg = (ASN1TaggedObject) seqout.getObjectAt(j); if (tg.getTagNo() == 0) { ASN1Sequence seqin = (ASN1Sequence) tg.getObject(); findCRL(seqin); } if (tg.getTagNo() == 1) { ASN1Sequence seqin = (ASN1Sequence) tg.getObject(); findOcsp(seqin); } } } } if (digestAttr == null) throw new IllegalArgumentException(MessageLocalization .getComposedMessage("authenticated.attribute.is.missing.the.digest")); ++next; } digestEncryptionAlgorithm = ((DERObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(next++)) .getObjectAt(0)).getId(); digest = ((DEROctetString) signerInfo.getObjectAt(next++)).getOctets(); if (next < signerInfo.size() && signerInfo.getObjectAt(next) instanceof DERTaggedObject) { DERTaggedObject taggedObject = (DERTaggedObject) signerInfo.getObjectAt(next); ASN1Set unat = ASN1Set.getInstance(taggedObject, false); AttributeTable attble = new AttributeTable(unat); Attribute ts = attble.get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken); if (ts != null && ts.getAttrValues().size() > 0) { ASN1Set attributeValues = ts.getAttrValues(); ASN1Sequence tokenSequence = ASN1Sequence.getInstance(attributeValues.getObjectAt(0)); ContentInfo contentInfo = new ContentInfo(tokenSequence); this.timeStampToken = new TimeStampToken(contentInfo); } } if (RSAdata != null || digestAttr != null) { if (provider == null || provider.startsWith("SunPKCS11")) messageDigest = MessageDigest.getInstance(getHashAlgorithm()); else messageDigest = MessageDigest.getInstance(getHashAlgorithm(), provider); } if (provider == null) sig = Signature.getInstance(getDigestAlgorithm()); else sig = Signature.getInstance(getDigestAlgorithm(), provider); sig.initVerify(signCert.getPublicKey()); } catch (Exception e) { throw new ExceptionConverter(e); } }
From source file:com.jlocksmith.util.ExtensionUtil.java
License:Open Source License
/** * Get Policy Mappings String Value//from w w w. j a v a 2 s . c o m * * @param bytes * * @return String * * @throws IOException */ private String getPolicyMappingsStringValue(byte[] bytes) throws IOException { // Get sequence of policy mappings ASN1Sequence policyMappings = (ASN1Sequence) toDERObject(bytes); StringBuffer strBuff = new StringBuffer(); // Get each policy mapping for (int i = 0, len = policyMappings.size(); i < len; i++) { ASN1Sequence policyMapping = (ASN1Sequence) policyMappings.getObjectAt(i); int pmLen = policyMapping.size(); strBuff.append( MessageFormat.format(localeUtil.getString("PolicyMapping"), new Object[] { "" + (i + 1) })); strBuff.append('\n'); if (pmLen > 0) { // Policy mapping issuer domain policy DERObjectIdentifier issuerDomainPolicy = (DERObjectIdentifier) policyMapping.getObjectAt(0); strBuff.append('\t'); strBuff.append(MessageFormat.format(localeUtil.getString("IssuerDomainPolicy"), new Object[] { issuerDomainPolicy.getId() })); strBuff.append('\n'); } if (pmLen > 1) { DERObjectIdentifier subjectDomainPolicy = (DERObjectIdentifier) policyMapping.getObjectAt(1); strBuff.append('\t'); strBuff.append(MessageFormat.format(localeUtil.getString("SubjectDomainPolicy"), new Object[] { subjectDomainPolicy.getId() })); strBuff.append('\n'); } } return strBuff.toString(); }
From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.X509CertDisplayBase_IT.java
License:Open Source License
protected String initPublicKeyAlgorithm() { // AlgorithmIdentifier aid = m_aX509.getSignatureAlgorithm(); DERObjectIdentifier oi = m_aX509.getSubjectPublicKeyInfo().getAlgorithmId().getObjectId(); return new String( "" + ((oi.equals(X509CertificateStructure.rsaEncryption)) ? "pkcs-1 rsaEncryption" : oi.getId())); }
From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.X509CertDisplayBase_IT.java
License:Open Source License
@Override public void prepareDisplayStrings(XFrame _xFrame, XComponent _xComp) throws IllegalArgumentException, Exception { m_xQc = (XOX_X509Certificate) UnoRuntime.queryInterface(XOX_X509Certificate.class, _xComp); if (m_xQc == null) throw (new IllegalArgumentException( "com.yacme.ext.oxsit.security.cert.XOX_X509CertificateDisplay#prepareDisplayStrings wrong argument")); ///*from w w w . ja v a2 s.c o m*/ m_aX509 = null; //remove old certificate //remove old data from HashMaps m_aExtensions.clear(); m_aExtensionLocalizedNames.clear(); m_aExtensionDisplayValues.clear(); m_aCriticalExtensions.clear(); m_aNotCriticalExtensions.clear(); ByteArrayInputStream as = new ByteArrayInputStream(m_xQc.getCertificateAttributes().getDEREncoded()); ASN1InputStream aderin = new ASN1InputStream(as); DERObject ado; try { ado = aderin.readObject(); m_aX509 = new X509CertificateStructure((ASN1Sequence) ado); //initializes the certificate display information initSubjectName(); m_sVersion = String.format("V%d", m_aX509.getVersion()); m_sSerialNumber = new String("" + m_aX509.getSerialNumber().getValue()); initIssuerName(); m_sNotValidBefore = initCertDate(m_aX509.getStartDate().getDate()); m_sNotValidAfter = initCertDate(m_aX509.getEndDate().getDate()); m_sSubjectPublicKeyAlgorithm = initPublicKeyAlgorithm(); m_sSubjectPublicKeyValue = initPublicKeyData(); m_sSignatureAlgorithm = initSignatureAlgorithm(); initThumbPrints(); //now initializes the Extension listing X509Extensions aX509Exts = m_aX509.getTBSCertificate().getExtensions(); //fill the internal extension HashMaps //at the same time we'll get the extension localized name from resources and //fill the display data MessageConfigurationAccess m_aRegAcc = null; m_aRegAcc = new MessageConfigurationAccess(m_xContext, m_xMCF); //FIXME: may be we need to adapt this to the context: the following is valid ONLY if this //object is instantiated from within a dialog, is not true if instantiated from a not UI method (e.g. from basic for example). IDynamicLogger aDlgH = null; CertificateExtensionDisplayHelper aHelper = new CertificateExtensionDisplayHelper(m_xContext, m_lTheLocale, m_sTimeLocaleString, m_sLocaleDateOfBirth, m_bDisplayOID, m_aLogger); for (Enumeration<DERObjectIdentifier> enume = aX509Exts.oids(); enume.hasMoreElements();) { DERObjectIdentifier aDERId = enume.nextElement(); String aTheOID = aDERId.getId(); X509Extension aext = aX509Exts.getExtension(aDERId); m_aExtensions.put(aTheOID, aext); //now grab the localized description try { m_aExtensionLocalizedNames.put(aTheOID, m_aRegAcc.getStringFromRegistry(aTheOID) + ((m_bDisplayOID) ? (" (OID: " + aTheOID.toString() + ")") : "")); } catch (com.sun.star.uno.Exception e) { m_aLogger.severe("setDEREncoded", e); m_aExtensionLocalizedNames.put(aTheOID, aTheOID); } //and decode this extension m_aExtensionDisplayValues.put(aTheOID, aHelper.examineExtension(aext, aDERId, this)); if (aext.isCritical()) m_aCriticalExtensions.put(aTheOID, aext); else m_aNotCriticalExtensions.put(aTheOID, aext); } m_aRegAcc.dispose(); } catch (IOException e) { m_aLogger.severe("setDEREncoded", e); } }
From source file:com.zimbra.cs.service.authenticator.CertUtil.java
License:Open Source License
String getSubjectAltNameOtherNameUPN() { Collection<List<?>> generalNames = null; try {/* w ww. j a v a 2 s.c o m*/ generalNames = cert.getSubjectAlternativeNames(); } catch (CertificateParsingException e) { ZimbraLog.account.warn(LOG_PREFIX + "unable to get subject alternative names", e); } if (generalNames == null) { return null; } ASN1InputStream decoder = null; try { // Check that the certificate includes the SubjectAltName extension for (List<?> generalName : generalNames) { Integer tag = (Integer) generalName.get(0); if (GeneralName.otherName == tag.intValue()) { // Value is encoded using ASN.1 decoder = new ASN1InputStream((byte[]) generalName.toArray()[1]); DEREncodable encoded = decoder.readObject(); DERSequence derSeq = (DERSequence) encoded; DERObjectIdentifier typeId = DERObjectIdentifier.getInstance(derSeq.getObjectAt(0)); String oid = typeId.getId(); String value = null; ASN1TaggedObject otherNameValue = ASN1TaggedObject.getInstance(derSeq.getObjectAt(1)); if (OID_UPN.equals(oid)) { ASN1TaggedObject upnValue = ASN1TaggedObject.getInstance(otherNameValue.getObject()); DERUTF8String str = DERUTF8String.getInstance(upnValue.getObject()); value = str.getString(); return value; } } } } catch (IOException e) { ZimbraLog.account.warn(LOG_PREFIX + "unable to process ASN.1 data", e); } finally { ByteUtil.closeStream(decoder); } return null; }
From source file:com.zimbra.cs.service.authenticator.CertUtil.java
License:Open Source License
private void printSubjectAlternativeNames(PrintStream outStream) throws Exception { final String UPN_DISPLAY = "Principal Name"; final String RFC822NAME_DISPLAY = "RFC822 Name"; final String DNSNAME_DISPLAY = "DNS Name"; outStream.format("X509v3 Subject Alternative Name: \n"); ASN1InputStream decoder = null; try {//from w w w . ja v a2 s . c o m Collection<List<?>> generalNames = cert.getSubjectAlternativeNames(); // Check that the certificate includes the SubjectAltName extension if (generalNames == null) { return; } /* OtherName ::= SEQUENCE { type-id OBJECT IDENTIFIER, value [0] EXPLICIT ANY DEFINED BY type-id } */ for (List<?> generalName : generalNames) { Integer tag = (Integer) generalName.get(0); if (GeneralName.otherName == tag.intValue()) { // Value is encoded using ASN.1 decoder = new ASN1InputStream((byte[]) generalName.toArray()[1]); DEREncodable encoded = decoder.readObject(); DERSequence derSeq = (DERSequence) encoded; DERObjectIdentifier typeId = DERObjectIdentifier.getInstance(derSeq.getObjectAt(0)); String oid = typeId.getId(); String value = null; ASN1TaggedObject otherNameValue = ASN1TaggedObject.getInstance(derSeq.getObjectAt(1)); if (OID_UPN.equals(oid)) { ASN1TaggedObject upnValue = ASN1TaggedObject.getInstance(otherNameValue.getObject()); DERUTF8String str = DERUTF8String.getInstance(upnValue.getObject()); value = str.getString(); } outStream.format(" [%d] %s(%s) = %s\n", tag, oid, UPN_DISPLAY, value); } else if (GeneralName.rfc822Name == tag.intValue()) { String value = (String) generalName.get(1); outStream.format(" [%d] %s = %s\n", tag, RFC822NAME_DISPLAY, value); } else if (GeneralName.dNSName == tag.intValue()) { String value = (String) generalName.get(1); outStream.format(" [%d] %s = %s\n", tag, DNSNAME_DISPLAY, value); } else { outStream.format(" [%d] - not yet supported\n", tag); } } } catch (CertificateParsingException e) { e.printStackTrace(); } finally { ByteUtil.closeStream(decoder); } }
From source file:de.fraunhofer.fokus.openeid.ca.AlgorithmIdentifier.java
License:Open Source License
public AlgorithmIdentifier(DERSequence algorithmInfo) { DERObjectIdentifier derOid = (DERObjectIdentifier) algorithmInfo.getObjectAt(0); algorithmOid = derOid.getId(); for (int i = 1; i < algorithmInfo.size(); i++) { parameter.add(algorithmInfo.getObjectAt(i)); }/*from ww w . j a va 2s .co m*/ }
From source file:de.fraunhofer.fokus.openeid.ca.ChipAuthenticationDomainParameterInfo.java
License:Open Source License
public ChipAuthenticationDomainParameterInfo(DERSequence chipDomainParameterInfoSequence) throws InvalidDomainParameter { DERObjectIdentifier derOid = (DERObjectIdentifier) chipDomainParameterInfoSequence.getObjectAt(0); protocolOid = derOid.getId(); DERSequence algorithm = (DERSequence) chipDomainParameterInfoSequence.getObjectAt(1); AlgorithmIdentifier id = new AlgorithmIdentifier(algorithm); int domainParameterValue = ((DERInteger) id.getParameter().get(0)).getValue().intValue(); domainParameter = StandardizedDomainParameters.getById(domainParameterValue); DERInteger derKeyId = (DERInteger) chipDomainParameterInfoSequence.getObjectAt(2); keyId = derKeyId.getValue().intValue(); }