List of usage examples for org.bouncycastle.asn1 ASN1Integer getInstance
public static ASN1Integer getInstance(Object obj)
From source file:com.guardtime.asn1.CertToken.java
License:Apache License
public Asn1CertToken(ASN1Sequence seq) { Enumeration en = seq.getObjects(); // Required elements version = ASN1Integer.getInstance(en.nextElement()); history = ASN1OctetString.getInstance(en.nextElement()); publishedData = Asn1PublishedData.getInstance(en.nextElement()); pubReference = ASN1Set.getInstance(en.nextElement()); // Optional elements while (en.hasMoreElements()) { ASN1TaggedObject obj = ASN1TaggedObject.getInstance(en.nextElement()); if (obj.getTagNo() == 0 && extensions == null) { extensions = Extensions.getInstance(obj, true); } else {/*from w w w . j a v a 2s . com*/ throw new IllegalArgumentException("invalid object in factory: " + obj); } } }
From source file:com.guardtime.asn1.CertTokenRequest.java
License:Apache License
public Asn1CertTokenRequest(ASN1Sequence seq) { Enumeration en = seq.getObjects(); // Required elements version = ASN1Integer.getInstance(en.nextElement()); historyIdentifier = ASN1Integer.getInstance(en.nextElement()); // Optional elements while (en.hasMoreElements()) { ASN1TaggedObject obj = ASN1TaggedObject.getInstance(en.nextElement()); if (obj.getTagNo() == 0 && extensions == null) { extensions = Extensions.getInstance(obj, true); } else {/*from w w w.j a va2s . c o m*/ throw new IllegalArgumentException("invalid object in factory: " + obj); } } }
From source file:com.guardtime.asn1.PublishedData.java
License:Apache License
public Asn1PublishedData(ASN1Sequence seq) { Enumeration en = seq.getObjects(); // Required elements publicationIdentifier = ASN1Integer.getInstance(en.nextElement()); publicationImprint = ASN1OctetString.getInstance(en.nextElement()); // Extra elements (not allowed) if (en.hasMoreElements()) { throw new IllegalArgumentException("invalid object in factory: " + en.nextElement()); }//from w w w . j a v a2 s .c om }
From source file:com.vvote.thirdparty.ximix.util.BLSKeyStore.java
License:Apache License
/** * Load the key store object from the passed in PKCS#12 encoding, using the passed in password. * * @param password the password to unlock the key store. * @param encoding the ASN.1 encoded bytes representing the PKCS#12 store. * @throws IOException on a parsing error. * @throws GeneralSecurityException if there's an exception decrypting the store. *///from ww w . ja v a 2 s . c o m public synchronized void load(char[] password, byte[] encoding) throws IOException, GeneralSecurityException { try { PKCS12PfxPdu pfx = new PKCS12PfxPdu(encoding); InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder() .setProvider("BC").build(password); ContentInfo[] infos = pfx.getContentInfos(); for (int i = 0; i != infos.length; i++) { if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) { PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider); PKCS12SafeBag[] bags = dataFact.getSafeBags(); Attribute[] attributes = bags[0].getAttributes(); X509CertificateHolder cert = (X509CertificateHolder) bags[0].getBagValue(); String keyID = getKeyID(attributes); BLS01PublicKeyParameters publicKeyParameters = BLSPublicKeyFactory .createKey(cert.getSubjectPublicKeyInfo()); paramsMap.put(keyID, publicKeyParameters.getParameters()); sequenceNoMap.put(keyID, ASN1Integer.getInstance( cert.getExtension(XimixObjectIdentifiers.ximixShareIdExtension).getParsedValue()) .getValue().intValue()); sharedPublicKeyMap.put(keyID, publicKeyParameters.getPk()); if (KeyUsage.fromExtensions(cert.getExtensions()).hasUsages(KeyUsage.digitalSignature)) { signingKeys.add(keyID); } } else { PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]); PKCS12SafeBag[] bags = dataFact.getSafeBags(); String keyID = getKeyID(bags[0].getAttributes()); PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue(); PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider); sharedPrivateKeyMap.put(keyID, ASN1Integer.getInstance(info.parsePrivateKey()).getValue()); } } } catch (PKCSException e) { throw new GeneralSecurityException("Unable to load key store: " + e.getMessage(), e); } }
From source file:com.vvote.thirdparty.ximix.util.PartialPublicKeyInfo.java
License:Apache License
private PartialPublicKeyInfo(ASN1Sequence seq) { this.sequenceNo = ASN1Integer.getInstance(seq.getObjectAt(0)).getValue().intValue(); this.partialKeyInfo = SubjectPublicKeyInfo.getInstance(seq.getObjectAt(1)); }
From source file:es.gob.afirma.applet.CMSInformation.java
License:Open Source License
/** * Obtiene la información de diferentes tipos de formatos. * @param doj Etiqueta ASN.1 de la que se obtienen los datos. * @param envelopeType Tipo de formato: * <li>0: EnvelopedData</li> * <li>1: AuthenticatedData</li> * <li>2: AuthEnvelopedData</li> * <li>3: SignedAndEnvelopedData</li> * <li>4: SignedData</li>// w w w . j a va 2 s . c o m * <li>5: Encrypted</li> * @param tipoDetalle Tipo de datos (literal) * @param signBinaryType Tipo de firmado binario (CADES o CMS) * @return Representación de los datos. */ private static String extractData(final ASN1TaggedObject doj, final int envelopeType, final String tipoDetalle, final int signBinaryType) { String detalle = ""; //$NON-NLS-1$ detalle = detalle + tipoDetalle + CR; ASN1Set rins = null; EncryptedContentInfo encryptedContentInfo = null; ASN1Set unprotectedAttrs = null; ASN1Integer version = null; AlgorithmIdentifier aid = null; ContentInfo ci = null; ASN1Set authAttrs = null; ASN1Set ds = null; ASN1Set signerInfosSd = null; switch (envelopeType) { case TYPE_ENVELOPED_DATA: final EnvelopedData enveloped = EnvelopedData.getInstance(doj.getObject()); version = enveloped.getVersion(); rins = enveloped.getRecipientInfos(); encryptedContentInfo = enveloped.getEncryptedContentInfo(); unprotectedAttrs = enveloped.getUnprotectedAttrs(); break; case TYPE_AUTHENTICATED_DATA: final AuthenticatedData authenticated = AuthenticatedData.getInstance(doj.getObject()); version = authenticated.getVersion(); rins = authenticated.getRecipientInfos(); aid = authenticated.getMacAlgorithm(); ci = authenticated.getEncapsulatedContentInfo(); authAttrs = authenticated.getAuthAttrs(); unprotectedAttrs = authenticated.getUnauthAttrs(); break; case TYPE_AUTHENTICATED_ENVELOPED_DATA: final AuthEnvelopedData authEnveloped = AuthEnvelopedData.getInstance(doj.getObject()); version = authEnveloped.getVersion(); rins = authEnveloped.getRecipientInfos(); encryptedContentInfo = authEnveloped.getAuthEncryptedContentInfo(); authAttrs = authEnveloped.getAuthAttrs(); unprotectedAttrs = authEnveloped.getUnauthAttrs(); break; case TYPE_SIGNED_ENVELOPED_DATA: final SignedAndEnvelopedData signedEnv = new SignedAndEnvelopedData((ASN1Sequence) doj.getObject()); version = signedEnv.getVersion(); rins = signedEnv.getRecipientInfos(); encryptedContentInfo = signedEnv.getEncryptedContentInfo(); signerInfosSd = signedEnv.getSignerInfos(); break; case TYPE_SIGNED_DATA: final SignedData signed = SignedData.getInstance(doj.getObject()); version = signed.getVersion(); ds = signed.getDigestAlgorithms(); ci = signed.getEncapContentInfo(); signerInfosSd = signed.getSignerInfos(); break; case TYPE_ENCRYPTED_DATA: final ASN1Sequence encrypted = (ASN1Sequence) doj.getObject(); version = ASN1Integer.getInstance(encrypted.getObjectAt(0)); encryptedContentInfo = EncryptedContentInfo.getInstance(encrypted.getObjectAt(1)); if (encrypted.size() == 3) { unprotectedAttrs = (ASN1Set) encrypted.getObjectAt(2); } break; default: throw new IllegalArgumentException("Tipo de sobre no soportado: " + envelopeType); //$NON-NLS-1$ } //obtenemos la version detalle = detalle + AppletMessages.getString("CMSInformation.1") + SP + version + CR; //$NON-NLS-1$ //recipientInfo if (rins != null) { if (envelopeType != TYPE_SIGNED_DATA && envelopeType != TYPE_ENCRYPTED_DATA && rins.size() > 0) { detalle = detalle + AppletMessages.getString("CMSInformation.13") + CR; //$NON-NLS-1$ } for (int i = 0; i < rins.size(); i++) { final KeyTransRecipientInfo kti = KeyTransRecipientInfo .getInstance(RecipientInfo.getInstance(rins.getObjectAt(i)).getInfo()); detalle = detalle + AppletMessages.getString("CMSInformation.14") + SP + (i + 1) + ":" + CR; //$NON-NLS-1$//$NON-NLS-2$ final AlgorithmIdentifier diAlg = kti.getKeyEncryptionAlgorithm(); //issuer y serial final IssuerAndSerialNumber iss = (IssuerAndSerialNumber) SignerIdentifier .getInstance(kti.getRecipientIdentifier().getId()).getId(); detalle = detalle + TB + AppletMessages.getString("CMSInformation.15") + SP //$NON-NLS-1$ + iss.getName().toString() + CR; detalle = detalle + TB + AppletMessages.getString("CMSInformation.16") + SP + iss.getSerialNumber() //$NON-NLS-1$ + CR; // el algoritmo de cifrado de los datos AOCipherAlgorithm algorithm = null; final AOCipherAlgorithm[] algos = AOCipherAlgorithm.values(); // obtenemos el algoritmo usado para cifrar la pass for (final AOCipherAlgorithm algo : algos) { if (algo.getOid().equals(diAlg.getAlgorithm().toString())) { algorithm = algo; } } if (algorithm != null) { detalle = detalle + TB + AppletMessages.getString("CMSInformation.17") + SP //$NON-NLS-1$ + algorithm.getName() + CR; } else { detalle = detalle + TB + AppletMessages.getString("CMSInformation.18") + SP //$NON-NLS-1$ + diAlg.getAlgorithm() + CR; } } } if (envelopeType == TYPE_ENVELOPED_DATA || envelopeType == TYPE_ENCRYPTED_DATA) { //obtenemos datos de los datos cifrados. detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$ detalle = detalle + getEncryptedContentInfo(encryptedContentInfo); } else if (envelopeType == TYPE_AUTHENTICATED_DATA && aid != null && ci != null) { // mac algorithm detalle = detalle + AppletMessages.getString("CMSInformation.20") + SP + aid.getAlgorithm() + CR; //$NON-NLS-1$ //digestAlgorithm final ASN1Sequence seq = (ASN1Sequence) doj.getObject(); final ASN1TaggedObject da = (ASN1TaggedObject) seq.getObjectAt(4); final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(da.getObject()); detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$ //obtenemos datos de los datos cifrados. detalle = detalle + AppletMessages.getString("CMSInformation.22") + SP + ci.getContentType() + CR; //$NON-NLS-1$ detalle = getObligatorieAtrib(signBinaryType, detalle, authAttrs); } else if (envelopeType == TYPE_AUTHENTICATED_ENVELOPED_DATA) { detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$ detalle = detalle + getEncryptedContentInfo(encryptedContentInfo); detalle = getObligatorieAtrib(signBinaryType, detalle, authAttrs); } else if (envelopeType == TYPE_SIGNED_ENVELOPED_DATA) { //algoritmo de firma final ASN1Sequence seq = (ASN1Sequence) doj.getObject(); final ASN1Set da = (ASN1Set) seq.getObjectAt(2); final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(da.getObjectAt(0)); detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$ //obtenemos datos de los datos cifrados. detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$ detalle = detalle + getEncryptedContentInfo(encryptedContentInfo); } else if (envelopeType == TYPE_SIGNED_DATA && ci != null && ds != null) { //algoritmo de firma final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(ds.getObjectAt(0)); detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$ detalle = detalle + AppletMessages.getString("CMSInformation.22") + SP + ci.getContentType() + CR; //$NON-NLS-1$ } //obtenemos lo atributos opcionales if (envelopeType != TYPE_SIGNED_ENVELOPED_DATA) { if (unprotectedAttrs == null) { detalle = detalle + AppletMessages.getString("CMSInformation.28") + CR; //$NON-NLS-1$ } else { final String atributos = getUnSignedAttributes(unprotectedAttrs.getObjects()); detalle = detalle + AppletMessages.getString("CMSInformation.29") + CR; //$NON-NLS-1$ detalle = detalle + atributos; } } else if ((envelopeType == TYPE_SIGNED_ENVELOPED_DATA || envelopeType == TYPE_SIGNED_DATA) && signerInfosSd != null) { //obtenemos el(los) firmate(s) if (signerInfosSd.size() > 0) { detalle = detalle + AppletMessages.getString("CMSInformation.30") + CR; //$NON-NLS-1$ } for (int i = 0; i < signerInfosSd.size(); i++) { final SignerInfo si = SignerInfo.getInstance(signerInfosSd.getObjectAt(i)); detalle = detalle + AppletMessages.getString("CMSInformation.31") + SP + (i + 1) + ":" + CR; //$NON-NLS-1$//$NON-NLS-2$ // version detalle = detalle + TB + AppletMessages.getString("CMSInformation.1") + SP + si.getVersion() + CR; //$NON-NLS-1$ //signerIdentifier final SignerIdentifier sident = si.getSID(); final IssuerAndSerialNumber iss = IssuerAndSerialNumber.getInstance(sident.getId()); detalle = detalle + TB + AppletMessages.getString("CMSInformation.15") + SP //$NON-NLS-1$ + iss.getName().toString() + CR; detalle = detalle + TB + AppletMessages.getString("CMSInformation.16") + SP + iss.getSerialNumber() //$NON-NLS-1$ + CR; //digestAlgorithm final AlgorithmIdentifier algId = si.getDigestAlgorithm(); detalle = detalle + TB + AppletMessages.getString("CMSInformation.35") + SP + algId.getAlgorithm() //$NON-NLS-1$ + CR; //obtenemos lo atributos obligatorios final ASN1Set sa = si.getAuthenticatedAttributes(); String satributes = ""; //$NON-NLS-1$ if (sa != null) { satributes = getsignedAttributes(sa, signBinaryType); } detalle = detalle + TB + AppletMessages.getString("CMSInformation.36") + CR; //$NON-NLS-1$ detalle = detalle + satributes; } } return detalle; }
From source file:es.gob.afirma.envelopers.cms.ValidateCMS.java
License:Open Source License
/** Método que verifica que es una firma de tipo "Encrypted data" * @param data/*from w w w . jav a 2s. co m*/ * Datos CMS. * @return si es de este tipo. */ static boolean isCMSEncryptedData(final byte[] data) { boolean isValid = true; try { final ASN1InputStream is = new ASN1InputStream(data); final ASN1Sequence dsq = (ASN1Sequence) is.readObject(); is.close(); final Enumeration<?> e = dsq.getObjects(); // Elementos que contienen los elementos OID Data final ASN1ObjectIdentifier doi = (ASN1ObjectIdentifier) e.nextElement(); if (!doi.equals(PKCSObjectIdentifiers.encryptedData)) { isValid = false; } else { // Contenido de Data final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); final ASN1Sequence asq = (ASN1Sequence) doj.getObject(); /* * Si no es de tipo EncryptedData se pasa al manejo de la * excepcion */ ASN1Integer.getInstance(asq.getObjectAt(0)); EncryptedContentInfo.getInstance(asq.getObjectAt(1)); } } catch (final Exception ex) { isValid = false; } return isValid; }
From source file:es.gob.afirma.signers.cades.CAdESValidator.java
License:Open Source License
/** Verifica si los datos proporcionados se corresponden con una estructura de tipo <i>EncryptedData</i>. * @param data Datos PKCS#7/CMS/CAdES./* ww w . j av a 2 s . c om*/ * @return <code>true</code> si los datos proporcionados se corresponden con una estructura de tipo <i>EncryptedData</i>, * <code>false</code> en caso contrario. * @throws IOException Si ocurren problemas relacionados con la lectura de los datos */ static boolean isCAdESEncryptedData(final byte[] data) throws IOException { boolean isValid = false; // LEEMOS EL FICHERO QUE NOS INTRODUCEN final ASN1InputStream is = new ASN1InputStream(data); final ASN1Sequence dsq; try { dsq = (ASN1Sequence) is.readObject(); } catch (final Exception e) { // No es una secuencia valida return false; } finally { is.close(); } final Enumeration<?> e = dsq.getObjects(); // Elementos que contienen los elementos OID Data final ASN1ObjectIdentifier doi = (ASN1ObjectIdentifier) e.nextElement(); if (doi.equals(PKCSObjectIdentifiers.encryptedData)) { isValid = true; } // Contenido de Data final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); final ASN1Sequence asq = (ASN1Sequence) doj.getObject(); try { /* Los resultados de las llamadas no se usan, solo es para verificar que la * conversion ha sido correcta. De no ser asi, se pasaria al manejo * de la excepcion. */ ASN1Integer.getInstance(asq.getObjectAt(0)); EncryptedContentInfo.getInstance(asq.getObjectAt(1)); if (asq.size() == 3) { asq.getObjectAt(2); } } catch (final Exception ex) { LOGGER.info("Los datos proporcionados no son de tipo EncryptedData: " + ex); //$NON-NLS-1$ return false; } return isValid; }
From source file:eu.europa.esig.dss.cades.signature.CAdESLevelBETSITS101733Test.java
License:Open Source License
@Override protected void onDocumentSigned(byte[] byteArray) { try {// w ww . ja v a2 s.co m CAdESSignature signature = new CAdESSignature(byteArray); assertNotNull(signature.getCmsSignedData()); ASN1InputStream asn1sInput = new ASN1InputStream(byteArray); ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject(); logger.info("SEQ : " + asn1Seq.toString()); assertEquals(2, asn1Seq.size()); ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0)); assertEquals(PKCSObjectIdentifiers.signedData, oid); logger.info("OID : " + oid.toString()); ASN1TaggedObject taggedObj = DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)); logger.info("TAGGED OBJ : " + taggedObj.toString()); ASN1Primitive object = taggedObj.getObject(); logger.info("OBJ : " + object.toString()); SignedData signedData = SignedData.getInstance(object); logger.info("SIGNED DATA : " + signedData.toString()); ASN1Set digestAlgorithms = signedData.getDigestAlgorithms(); logger.info("DIGEST ALGOS : " + digestAlgorithms.toString()); ContentInfo encapContentInfo = signedData.getEncapContentInfo(); logger.info("ENCAPSULATED CONTENT INFO : " + encapContentInfo.getContentType() + " " + encapContentInfo.getContent()); ASN1Set certificates = signedData.getCertificates(); logger.info("CERTIFICATES (" + certificates.size() + ") : " + certificates); List<X509Certificate> foundCertificates = new ArrayList<X509Certificate>(); for (int i = 0; i < certificates.size(); i++) { ASN1Sequence seqCertif = ASN1Sequence.getInstance(certificates.getObjectAt(i)); logger.info("SEQ cert " + i + " : " + seqCertif); X509CertificateHolder certificateHolder = new X509CertificateHolder(seqCertif.getEncoded()); CertificateToken certificate = DSSASN1Utils.getCertificate(certificateHolder); X509Certificate x509Certificate = certificate.getCertificate(); x509Certificate.checkValidity(); logger.info("Cert " + i + " : " + certificate); foundCertificates.add(x509Certificate); } ASN1Set crLs = signedData.getCRLs(); logger.info("CRLs : " + crLs); ASN1Set signerInfosAsn1 = signedData.getSignerInfos(); logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString()); assertEquals(1, signerInfosAsn1.size()); ASN1Sequence seqSignedInfo = ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)); SignerInfo signedInfo = SignerInfo.getInstance(seqSignedInfo); logger.info("SIGNER INFO : " + signedInfo.toString()); SignerIdentifier sid = signedInfo.getSID(); logger.info("SIGNER IDENTIFIER : " + sid.getId()); IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber.getInstance(signedInfo.getSID()); logger.info("ISSUER AND SN : " + issuerAndSerialNumber.toString()); BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue(); X509Certificate signerCertificate = null; for (X509Certificate x509Certificate : foundCertificates) { // TODO check issuer name if (serial.equals(x509Certificate.getSerialNumber())) { signerCertificate = x509Certificate; } } assertNotNull(signerCertificate); ASN1OctetString encryptedDigest = signedInfo.getEncryptedDigest(); logger.info("ENCRYPT DIGEST : " + encryptedDigest.toString()); ASN1Sequence seq = ASN1Sequence.getInstance(object); ASN1Integer version = ASN1Integer.getInstance(seq.getObjectAt(0)); logger.info("VERSION : " + version.toString()); ASN1Set digestManualSet = ASN1Set.getInstance(seq.getObjectAt(1)); logger.info("DIGEST SET : " + digestManualSet.toString()); assertEquals(digestAlgorithms, digestManualSet); ASN1Sequence seqDigest = ASN1Sequence.getInstance(digestManualSet.getObjectAt(0)); // assertEquals(1, seqDigest.size()); ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier.getInstance(seqDigest.getObjectAt(0)); assertEquals(new ASN1ObjectIdentifier(DigestAlgorithm.SHA256.getOid()), oidDigestAlgo); ASN1Sequence seqEncapsulatedInfo = ASN1Sequence.getInstance(seq.getObjectAt(2)); logger.info("ENCAPSULATED INFO : " + seqEncapsulatedInfo.toString()); ASN1ObjectIdentifier oidContentType = ASN1ObjectIdentifier .getInstance(seqEncapsulatedInfo.getObjectAt(0)); logger.info("OID CONTENT TYPE : " + oidContentType.toString()); ASN1TaggedObject taggedContent = DERTaggedObject.getInstance(seqEncapsulatedInfo.getObjectAt(1)); ASN1OctetString contentOctetString = ASN1OctetString.getInstance(taggedContent.getObject()); String content = new String(contentOctetString.getOctets()); assertEquals(HELLO_WORLD, content); logger.info("CONTENT : " + content); byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA256, HELLO_WORLD.getBytes()); String encodeHexDigest = Hex.toHexString(digest); logger.info("CONTENT DIGEST COMPUTED : " + encodeHexDigest); ASN1Set authenticatedAttributes = signedInfo.getAuthenticatedAttributes(); logger.info("AUTHENTICATED ATTRIBUTES : " + authenticatedAttributes.toString()); // ASN1Sequence seqAuthAttrib = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(0)); logger.info("Nb Auth Attributes : " + authenticatedAttributes.size()); String embeddedDigest = ""; for (int i = 0; i < authenticatedAttributes.size(); i++) { ASN1Sequence authAttrSeq = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(i)); logger.info(authAttrSeq.toString()); ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(authAttrSeq.getObjectAt(0)); if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attrOid)) { ASN1Set setMessageDigest = ASN1Set.getInstance(authAttrSeq.getObjectAt(1)); ASN1OctetString asn1ObjString = ASN1OctetString.getInstance(setMessageDigest.getObjectAt(0)); embeddedDigest = Hex.toHexString(asn1ObjString.getOctets()); } } assertEquals(encodeHexDigest, embeddedDigest); ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest(); String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets()); logger.info("SIGNATURE VALUE : " + signatureValue); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, signerCertificate); byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets()); ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted); ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject(); logger.info("Decrypted : " + seqDecrypt); DigestInfo digestInfo = new DigestInfo(seqDecrypt); assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm()); String decryptedDigestEncodeBase64 = Utils.toBase64(digestInfo.getDigest()); logger.info("Decrypted Base64 : " + decryptedDigestEncodeBase64); byte[] encoded = signedInfo.getAuthenticatedAttributes().getEncoded(); MessageDigest messageDigest = MessageDigest.getInstance(DigestAlgorithm.SHA256.getName()); byte[] digestOfAuthenticatedAttributes = messageDigest.digest(encoded); String computedDigestEncodeBase64 = Utils.toBase64(digestOfAuthenticatedAttributes); logger.info("Computed Base64 : " + computedDigestEncodeBase64); assertEquals(decryptedDigestEncodeBase64, computedDigestEncodeBase64); Utils.closeQuietly(asn1sInput); Utils.closeQuietly(inputDecrypted); } catch (Exception e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } }
From source file:eu.europa.esig.dss.cades.signature.CAdESLevelBTest.java
License:Open Source License
@Override protected void onDocumentSigned(byte[] byteArray) { try {//from ww w. j a va2 s . c o m CAdESSignature signature = new CAdESSignature(byteArray); assertNotNull(signature.getCmsSignedData()); ASN1InputStream asn1sInput = new ASN1InputStream(byteArray); ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject(); logger.info("SEQ : " + asn1Seq.toString()); assertEquals(2, asn1Seq.size()); ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0)); assertEquals(PKCSObjectIdentifiers.signedData, oid); logger.info("OID : " + oid.toString()); ASN1TaggedObject taggedObj = DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)); logger.info("TAGGED OBJ : " + taggedObj.toString()); ASN1Primitive object = taggedObj.getObject(); logger.info("OBJ : " + object.toString()); SignedData signedData = SignedData.getInstance(object); logger.info("SIGNED DATA : " + signedData.toString()); ASN1Set digestAlgorithms = signedData.getDigestAlgorithms(); logger.info("DIGEST ALGOS : " + digestAlgorithms.toString()); ContentInfo encapContentInfo = signedData.getEncapContentInfo(); logger.info("ENCAPSULATED CONTENT INFO : " + encapContentInfo.getContentType() + " " + encapContentInfo.getContent()); ASN1Set certificates = signedData.getCertificates(); logger.info("CERTIFICATES (" + certificates.size() + ") : " + certificates); List<X509Certificate> foundCertificates = new ArrayList<X509Certificate>(); for (int i = 0; i < certificates.size(); i++) { ASN1Sequence seqCertif = ASN1Sequence.getInstance(certificates.getObjectAt(i)); logger.info("SEQ cert " + i + " : " + seqCertif); X509CertificateHolder certificateHolder = new X509CertificateHolder(seqCertif.getEncoded()); X509Certificate certificate = new JcaX509CertificateConverter() .setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder); certificate.checkValidity(); logger.info("Cert " + i + " : " + certificate); foundCertificates.add(certificate); } ASN1Set crLs = signedData.getCRLs(); logger.info("CRLs : " + crLs); ASN1Set signerInfosAsn1 = signedData.getSignerInfos(); logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString()); assertEquals(1, signerInfosAsn1.size()); ASN1Sequence seqSignedInfo = ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)); SignerInfo signedInfo = SignerInfo.getInstance(seqSignedInfo); logger.info("SIGNER INFO : " + signedInfo.toString()); SignerIdentifier sid = signedInfo.getSID(); logger.info("SIGNER IDENTIFIER : " + sid.getId()); IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber.getInstance(signedInfo.getSID()); logger.info("ISSUER AND SN : " + issuerAndSerialNumber.toString()); BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue(); X509Certificate signerCertificate = null; for (X509Certificate x509Certificate : foundCertificates) { // TODO check issuer name if (serial.equals(x509Certificate.getSerialNumber())) { signerCertificate = x509Certificate; } } assertNotNull(signerCertificate); ASN1OctetString encryptedDigest = signedInfo.getEncryptedDigest(); logger.info("ENCRYPT DIGEST : " + encryptedDigest.toString()); ASN1Sequence seq = ASN1Sequence.getInstance(object); ASN1Integer version = ASN1Integer.getInstance(seq.getObjectAt(0)); logger.info("VERSION : " + version.toString()); ASN1Set digestManualSet = ASN1Set.getInstance(seq.getObjectAt(1)); logger.info("DIGEST SET : " + digestManualSet.toString()); assertEquals(digestAlgorithms, digestManualSet); ASN1Sequence seqDigest = ASN1Sequence.getInstance(digestManualSet.getObjectAt(0)); // assertEquals(1, seqDigest.size()); ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier.getInstance(seqDigest.getObjectAt(0)); assertEquals(new ASN1ObjectIdentifier(DigestAlgorithm.SHA256.getOid()), oidDigestAlgo); ASN1Sequence seqEncapsulatedInfo = ASN1Sequence.getInstance(seq.getObjectAt(2)); logger.info("ENCAPSULATED INFO : " + seqEncapsulatedInfo.toString()); ASN1ObjectIdentifier oidContentType = ASN1ObjectIdentifier .getInstance(seqEncapsulatedInfo.getObjectAt(0)); logger.info("OID CONTENT TYPE : " + oidContentType.toString()); ASN1TaggedObject taggedContent = DERTaggedObject.getInstance(seqEncapsulatedInfo.getObjectAt(1)); ASN1OctetString contentOctetString = ASN1OctetString.getInstance(taggedContent.getObject()); String content = new String(contentOctetString.getOctets()); assertEquals(HELLO_WORLD, content); logger.info("CONTENT : " + content); byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA256, HELLO_WORLD.getBytes()); String encodeHexDigest = Hex.toHexString(digest); logger.info("CONTENT DIGEST COMPUTED : " + encodeHexDigest); ASN1Set authenticatedAttributes = signedInfo.getAuthenticatedAttributes(); logger.info("AUTHENTICATED ATTRIBUTES : " + authenticatedAttributes.toString()); // ASN1Sequence seqAuthAttrib = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(0)); logger.info("Nb Auth Attributes : " + authenticatedAttributes.size()); String embeddedDigest = StringUtils.EMPTY; for (int i = 0; i < authenticatedAttributes.size(); i++) { ASN1Sequence authAttrSeq = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(i)); logger.info(authAttrSeq.toString()); ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(authAttrSeq.getObjectAt(0)); if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attrOid)) { ASN1Set setMessageDigest = ASN1Set.getInstance(authAttrSeq.getObjectAt(1)); ASN1OctetString asn1ObjString = ASN1OctetString.getInstance(setMessageDigest.getObjectAt(0)); embeddedDigest = Hex.toHexString(asn1ObjString.getOctets()); } } assertEquals(encodeHexDigest, embeddedDigest); ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest(); String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets()); logger.info("SIGNATURE VALUE : " + signatureValue); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, signerCertificate); byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets()); ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted); ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject(); logger.info("Decrypted : " + seqDecrypt); DigestInfo digestInfo = new DigestInfo(seqDecrypt); assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm()); String decryptedDigestEncodeBase64 = Base64.encodeBase64String(digestInfo.getDigest()); logger.info("Decrypted Base64 : " + decryptedDigestEncodeBase64); byte[] encoded = signedInfo.getAuthenticatedAttributes().getEncoded(); MessageDigest messageDigest = MessageDigest.getInstance(DigestAlgorithm.SHA256.getName()); byte[] digestOfAuthenticatedAttributes = messageDigest.digest(encoded); String computedDigestEncodeBase64 = Base64.encodeBase64String(digestOfAuthenticatedAttributes); logger.info("Computed Base64 : " + computedDigestEncodeBase64); assertEquals(decryptedDigestEncodeBase64, computedDigestEncodeBase64); IOUtils.closeQuietly(asn1sInput); IOUtils.closeQuietly(inputDecrypted); } catch (Exception e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } }