List of usage examples for org.bouncycastle.asn1 DEROctetString DEROctetString
public DEROctetString(ASN1Encodable obj) throws IOException
From source file:es.gob.afirma.signers.multi.cades.CAdESTriPhaseCounterSigner.java
License:Open Source License
/** Genera un signerInfo específico utilizando los * datos necesarios para crearlo. Se utiliza siempre que no se sabe cual es * el signerInfo que se debe firmar.</br> * @param parameters Parámetros necesarios para firmar un determinado SignerInfo hoja. * @param si SignerInfo del que se debe recoger la información para * realizar la contrafirma específica. * @param key Clave privada a usar para firmar * @param contentType Tipo de contenido definido por su OID. * @param contentDescription Descripción textual del tipo de contenido firmado. * @return SignerInfo contrafirmado./*from w w w. j a va2s.co m*/ * @throws java.security.NoSuchAlgorithmException * @throws java.io.IOException * @throws java.security.cert.CertificateException */ private SignerInfo generateSignerInfo(final String signatureAlgorithm, final SignerInfo si, final java.security.cert.Certificate[] certChain, final String contentType, final String contentDescription, final AdESPolicy policy, final boolean signingCertificateV2) throws NoSuchAlgorithmException, IOException, CertificateException { // buscamos que timo de algoritmo es y lo codificamos con su OID final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(signatureAlgorithm); // authenticatedAttributes final ASN1EncodableVector contextExcepcific = CAdESUtils.generateSignerInfo((X509Certificate) certChain[0], digestAlgorithm, si.getEncryptedDigest().getOctets(), policy, signingCertificateV2, null, new Date(), false, contentType, contentDescription); final ASN1Set signedAttr = SigUtils.getAttributeSet(new AttributeTable(contextExcepcific)); // Anadimos los SignedAttributes a la lista en la posicion adecuada this.signedDatas.add(this.counterIndex, signedAttr.getEncoded(ASN1Encoding.DER)); // Obtenemos el sustituto del PKCS#1, relleno con el numero de contrafirma final ASN1OctetString sign2 = new DEROctetString(firma()); // Incrementamos el indice de contrafirmas this.counterIndex = this.counterIndex + 1; if (this.counterIndex > 9) { throw new UnsupportedOperationException("No se soportan mas de 10 contrafirmas en una misma firma"); //$NON-NLS-1$ } // AlgorithmIdentifier final AlgorithmIdentifier digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm)); // digEncryptionAlgorithm final AlgorithmIdentifier encAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID("RSA")); //$NON-NLS-1$ // 5. SIGNERINFO // raiz de la secuencia de SignerInfo final TBSCertificateStructure tbs = TBSCertificateStructure .getInstance(ASN1Primitive.fromByteArray(((X509Certificate) certChain[0]).getTBSCertificate())); final IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(X500Name.getInstance(tbs.getIssuer()), tbs.getSerialNumber().getValue()); final SignerIdentifier identifier = new SignerIdentifier(encSid); // UNAUTHENTICATEDATTRIBUTES final ASN1Set unsignedAttr = SigUtils.getAttributeSet(new AttributeTable(contextExcepcific)); return new SignerInfo(identifier, digAlgId, unsignedAttr, encAlgId, sign2, null); }
From source file:es.gob.afirma.signers.pades.ltv.PdfDocumentSecurityStore.java
License:Open Source License
synchronized int registerOcspBasicResp(final byte basicResp[]) throws IOException { final ASN1EncodableVector v2 = new ASN1EncodableVector(); v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic); v2.add(new DEROctetString(basicResp)); final ASN1EncodableVector v3 = new ASN1EncodableVector(); v3.add(new ASN1Enumerated(0)); v3.add(new DERTaggedObject(true, 0, new DERSequence(v2))); return registerOcspResp(new DERSequence(v3).getEncoded()); }
From source file:es.uji.security.crypto.pdf.PdfPKCS7TSA.java
License:Mozilla Public License
/** * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes * in the signerInfo can also be set, OR a time-stamp-authority client * may be provided. * @param secondDigest the digest in the authenticatedAttributes * @param signingTime the signing time in the authenticatedAttributes * @param tsaUrl TSAClient - null or an optional time stamp authority client * @return byte[] the bytes for the PKCS7SignedData object * @since 2.1.6 *//*from w w w.j a va 2 s .com*/ public byte[] getEncodedPKCS7(byte secondDigest[], Calendar signingTime, String tsaUrl, byte[] ocsp) { try { if (externalDigest != null) { digest = externalDigest; if (RSAdata != null) RSAdata = externalRSAdata; } else if (externalRSAdata != null && RSAdata != null) { RSAdata = externalRSAdata; sig.update(RSAdata); digest = sig.sign(); } else { if (RSAdata != null) { RSAdata = messageDigest.digest(); sig.update(RSAdata); } digest = sig.sign(); } // Create the set of Hash algorithms ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector(); for (Iterator it = digestalgos.iterator(); it.hasNext();) { ASN1EncodableVector algos = new ASN1EncodableVector(); algos.add(new DERObjectIdentifier((String) it.next())); algos.add(DERNull.INSTANCE); digestAlgorithms.add(new DERSequence(algos)); } // Create the contentInfo. ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(ID_PKCS7_DATA)); if (RSAdata != null) v.add(new DERTaggedObject(0, new DEROctetString(RSAdata))); DERSequence contentinfo = new DERSequence(v); // Get all the certificates // v = new ASN1EncodableVector(); for (Iterator i = certs.iterator(); i.hasNext();) { ASN1InputStream tempstream = new ASN1InputStream( new ByteArrayInputStream(((X509Certificate) i.next()).getEncoded())); v.add(tempstream.readObject()); } DERSet dercertificates = new DERSet(v); // Create signerinfo structure. // ASN1EncodableVector signerinfo = new ASN1EncodableVector(); // Add the signerInfo version // signerinfo.add(new DERInteger(signerversion)); v = new ASN1EncodableVector(); v.add(getIssuer(signCert.getTBSCertificate())); v.add(new DERInteger(signCert.getSerialNumber())); signerinfo.add(new DERSequence(v)); // Add the digestAlgorithm v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(digestAlgorithm)); v.add(new DERNull()); signerinfo.add(new DERSequence(v)); // add the authenticated attribute if present if (secondDigest != null && signingTime != null) { signerinfo.add(new DERTaggedObject(false, 0, getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp))); } // Add the digestEncryptionAlgorithm v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(digestEncryptionAlgorithm)); v.add(new DERNull()); signerinfo.add(new DERSequence(v)); // Add the digest signerinfo.add(new DEROctetString(digest)); // When requested, go get and add the timestamp. May throw an exception. // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15 // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest if (tsaUrl != null) { byte[] tsImprint = MessageDigest.getInstance("SHA-1").digest(digest); TSResponse response = TimeStampFactory.getTimeStampResponse(tsaUrl, tsImprint, false); byte[] tsToken = response.getEncodedToken(); //Strip the status code out of the response, the adobe validator requieres it. //TODO: Research about this. byte[] status = { 0x30, (byte) 0x82, 0x03, (byte) 0xA7, 0x30, 0x03, 0x02, 0x01, 0x00 }; byte[] modTsToken = new byte[tsToken.length - status.length]; System.arraycopy(tsToken, status.length, modTsToken, 0, tsToken.length - status.length); if (modTsToken != null) { ASN1EncodableVector unauthAttributes = buildUnauthenticatedAttributes(modTsToken); if (unauthAttributes != null) { signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unauthAttributes))); } } } // Finally build the body out of all the components above ASN1EncodableVector body = new ASN1EncodableVector(); body.add(new DERInteger(version)); body.add(new DERSet(digestAlgorithms)); body.add(contentinfo); body.add(new DERTaggedObject(false, 0, dercertificates)); if (!crls.isEmpty()) { v = new ASN1EncodableVector(); for (Iterator i = crls.iterator(); i.hasNext();) { ASN1InputStream t = new ASN1InputStream( new ByteArrayInputStream(((X509CRL) i.next()).getEncoded())); v.add(t.readObject()); } DERSet dercrls = new DERSet(v); body.add(new DERTaggedObject(false, 1, dercrls)); } // Only allow one signerInfo body.add(new DERSet(new DERSequence(signerinfo))); // Now we have the body, wrap it in it's PKCS7Signed shell // and return it // ASN1EncodableVector whole = new ASN1EncodableVector(); whole.add(new DERObjectIdentifier(ID_PKCS7_SIGNED_DATA)); whole.add(new DERTaggedObject(0, new DERSequence(body))); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream dout = new ASN1OutputStream(bOut); dout.writeObject(new DERSequence(whole)); dout.close(); return bOut.toByteArray(); } catch (Exception e) { throw new ExceptionConverter(e); } }
From source file:es.uji.security.crypto.pdf.PdfPKCS7TSA.java
License:Mozilla Public License
private DERSet getAuthenticatedAttributeSet(byte secondDigest[], Calendar signingTime, byte[] ocsp) { try {/* w ww . j a v a2 s . c om*/ ASN1EncodableVector attribute = new ASN1EncodableVector(); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(ID_CONTENT_TYPE)); v.add(new DERSet(new DERObjectIdentifier(ID_PKCS7_DATA))); attribute.add(new DERSequence(v)); v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(ID_SIGNING_TIME)); v.add(new DERSet(new DERUTCTime(signingTime.getTime()))); attribute.add(new DERSequence(v)); v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(ID_MESSAGE_DIGEST)); v.add(new DERSet(new DEROctetString(secondDigest))); attribute.add(new DERSequence(v)); if (ocsp != null) { v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(ID_ADBE_REVOCATION)); DEROctetString doctet = new DEROctetString(ocsp); ASN1EncodableVector vo1 = new ASN1EncodableVector(); ASN1EncodableVector v2 = new ASN1EncodableVector(); v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic); v2.add(doctet); DEREnumerated den = new DEREnumerated(0); ASN1EncodableVector v3 = new ASN1EncodableVector(); v3.add(den); v3.add(new DERTaggedObject(true, 0, new DERSequence(v2))); vo1.add(new DERSequence(v3)); v.add(new DERSet(new DERSequence(new DERTaggedObject(true, 1, new DERSequence(vo1))))); attribute.add(new DERSequence(v)); } else if (!crls.isEmpty()) { v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(ID_ADBE_REVOCATION)); ASN1EncodableVector v2 = new ASN1EncodableVector(); for (Iterator i = crls.iterator(); i.hasNext();) { ASN1InputStream t = new ASN1InputStream( new ByteArrayInputStream(((X509CRL) i.next()).getEncoded())); v2.add(t.readObject()); } v.add(new DERSet(new DERSequence(new DERTaggedObject(true, 0, new DERSequence(v2))))); attribute.add(new DERSequence(v)); } return new DERSet(attribute); } catch (Exception e) { throw new ExceptionConverter(e); } }
From source file:eu.betaas.taas.securitymanager.common.ec.ECKeyPairGen.java
License:Apache License
/** * A method to reconstruct an ECPublicKey from a SubjectPublicKeyInfo of a * certificate /*from w w w . j av a 2s.c o m*/ * @param info: SubjectPublicKeyInfo in a X509Certificate * @return: ECPublicKeyParameters */ public static ECPublicKeyParameters generateECPublicKey(SubjectPublicKeyInfo info) { X962Parameters as = (X962Parameters) info.getAlgorithm().getParameters(); DERSequence aa = (DERSequence) as.getParameters(); Enumeration en = aa.getObjects(); ECCurve curve = null; org.bouncycastle.math.ec.ECPoint g = null; byte[] seed = null; BigInteger h = null; BigInteger n = null; while (en.hasMoreElements()) { Object oen = en.nextElement(); if (oen instanceof X9Curve) { curve = ((X9Curve) oen).getCurve(); seed = ((X9Curve) oen).getSeed(); } else if (oen instanceof X9ECPoint) { g = ((X9ECPoint) oen).getPoint(); } else if (oen instanceof ASN1Integer) { BigInteger xoen = ((ASN1Integer) oen).getValue(); if (xoen.equals(BigInteger.ONE)) h = xoen; else n = xoen; } } ASN1OctetString key = new DEROctetString(info.getPublicKeyData().getBytes()); X9ECPoint derQ = new X9ECPoint(curve, key); ECDomainParameters dParams = new ECDomainParameters(curve, g, n, h, seed); return new ECPublicKeyParameters(derQ.getPoint(), dParams); }
From source file:eu.emi.security.authn.x509.helpers.proxy.ProxySAMLExtension.java
License:Open Source License
/** * Used to generate an instance form the SAML assertion in String * format.// w w w.ja v a 2 s . c o m * * @param samlString */ public ProxySAMLExtension(String samlString) { try { this.saml = new DEROctetString(samlString.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 encoding is unsupported - JDK problem", e); } }
From source file:eu.europa.ec.markt.dss.DSSRevocationUtils.java
License:Open Source License
/** * Convert a BasicOCSPResp in OCSPResp (connection status is set to SUCCESSFUL). * * @param basicOCSPResp//from www. j a va2s. c o m * @return */ public static final OCSPResp fromBasicToResp(final byte[] basicOCSPResp) { final OCSPResponseStatus responseStatus = new OCSPResponseStatus(OCSPResponseStatus.SUCCESSFUL); final DEROctetString derBasicOCSPResp = new DEROctetString(basicOCSPResp); final ResponseBytes responseBytes = new ResponseBytes(OCSPObjectIdentifiers.id_pkix_ocsp_basic, derBasicOCSPResp); final OCSPResponse ocspResponse = new OCSPResponse(responseStatus, responseBytes); final OCSPResp ocspResp = new OCSPResp(ocspResponse); //!!! todo to be checked: System.out.println("===> RECREATED: " + ocspResp.hashCode()); return ocspResp; }
From source file:eu.europa.ec.markt.dss.signature.cades.CAdESLevelBaselineB.java
License:Open Source License
private void addSignaturePolicyId(final SignatureParameters parameters, final ASN1EncodableVector signedAttributes) { Policy policy = parameters.bLevel().getSignaturePolicy(); if (policy != null && policy.getId() != null) { final String policyId = policy.getId(); SignaturePolicyIdentifier sigPolicy = null; if (!"".equals(policyId)) { // explicit final ASN1ObjectIdentifier derOIPolicyId = new ASN1ObjectIdentifier(policyId); final ASN1ObjectIdentifier oid = policy.getDigestAlgorithm().getOid(); final AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(oid); OtherHashAlgAndValue otherHashAlgAndValue = new OtherHashAlgAndValue(algorithmIdentifier, new DEROctetString(policy.getDigestValue())); sigPolicy = new SignaturePolicyIdentifier( new SignaturePolicyId(derOIPolicyId, otherHashAlgAndValue)); } else {// implicit sigPolicy = new SignaturePolicyIdentifier(); }/* w ww . ja v a2s . co m*/ final DERSet attrValues = new DERSet(sigPolicy); final Attribute attribute = new Attribute(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId, attrValues); signedAttributes.add(attribute); } }
From source file:eu.europa.ec.markt.dss.signature.cades.CadesLevelBaselineLTATimestampExtractor.java
License:Open Source License
/** * The field certificatesHashIndex is a sequence of octet strings. Each one contains the hash value of one * instance of CertificateChoices within certificates field of the root SignedData. A hash value for * every instance of CertificateChoices, as present at the time when the corresponding archive time-stamp is * requested, shall be included in certificatesHashIndex. No other hash value shall be included in this field. * * @param cAdESSignature/*from w w w. java 2s. co m*/ * @return * @throws eu.europa.ec.markt.dss.exception.DSSException */ private ASN1Sequence getCertificatesHashIndex(CAdESSignature cAdESSignature) throws DSSException { final ASN1EncodableVector certificatesHashIndexVector = new ASN1EncodableVector(); final List<CertificateToken> certificateTokens = cAdESSignature .getCertificatesWithinSignatureAndTimestamps(); for (final CertificateToken certificateToken : certificateTokens) { final byte[] encodedCertificate = certificateToken.getEncoded(); final byte[] digest = DSSUtils.digest(hashIndexDigestAlgorithm, encodedCertificate); if (LOG.isDebugEnabled()) { LOG.debug("Adding to CertificatesHashIndex DSS-Identifier: {} with hash {}", certificateToken.getDSSId(), DSSUtils.encodeHexString(digest)); } final DEROctetString derOctetStringDigest = new DEROctetString(digest); certificatesHashIndexVector.add(derOctetStringDigest); } return new DERSequence(certificatesHashIndexVector); }
From source file:eu.europa.ec.markt.dss.signature.cades.CadesLevelBaselineLTATimestampExtractor.java
License:Open Source License
/** * The field certificatesHashIndex is a sequence of octet strings. Each one contains the hash value of one * instance of CertificateChoices within certificates field of the root SignedData. A hash value for * every instance of CertificateChoices, as present at the time when the corresponding archive time-stamp is * requested, shall be included in certificatesHashIndex. No other hash value shall be included in this field. * * @param cAdESSignature/*from ww w . ja va 2 s .co m*/ * @return * @throws eu.europa.ec.markt.dss.exception.DSSException */ @SuppressWarnings("unchecked") private ASN1Sequence getVerifiedCertificatesHashIndex(CAdESSignature cAdESSignature, TimestampToken timestampToken) throws DSSException { final ASN1Sequence certHashes = getCertificatesHashIndex(timestampToken); final ArrayList<DEROctetString> certHashesList = Collections.list(certHashes.getObjects()); final List<CertificateToken> certificates = cAdESSignature.getCertificatesWithinSignatureAndTimestamps(); for (final CertificateToken certificateToken : certificates) { final byte[] encodedCertificate = certificateToken.getEncoded(); final byte[] digest = DSSUtils.digest(hashIndexDigestAlgorithm, encodedCertificate); final DEROctetString derOctetStringDigest = new DEROctetString(digest); if (certHashesList.remove(derOctetStringDigest)) { // attribute present in signature and in timestamp LOG.debug("Cert {} present in timestamp", certificateToken.getAbbreviation()); } else { LOG.debug("Cert {} not present in timestamp", certificateToken.getAbbreviation()); } } if (!certHashesList.isEmpty()) { LOG.error("{} attribute hash in Cert Hashes have not been found in document attributes: {}", certHashesList.size(), certHashesList); // return a empty DERSequence to screw up the hash return new DERSequence(); } return certHashes; }