List of usage examples for org.bouncycastle.asn1.x509 X509ObjectIdentifiers id_SHA1
ASN1ObjectIdentifier id_SHA1
To view the source code for org.bouncycastle.asn1.x509 X509ObjectIdentifiers id_SHA1.
Click Source Link
OID: 1.3.14.3.2.27
From source file:ch.bfh.unicert.certimport.CertificateIssuer.java
License:GNU General Public License
public Certificate createClientCertificate(IdentityData id, String keyStorePath, PublicKey pk, int validity, String applicationIdentifier, String[] roles, String uniBoardWsdlURL, String uniBoardServiceURL, String section) throws CertificateCreationException { X509Certificate caCert;/*from www . j ava 2s . c o m*/ RSAPrivateCrtKey privKey; try { caCert = this.readIssuerCertificate(this.issuerId); privKey = this.readPrivateKey(this.issuerId, this.privKeyPass); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) { logger.log(Level.SEVERE, null, ex); throw new CertificateCreationException("230 Could not create client certificate. Key error"); } RSAPrivateCrtKeyParameters cipherParams = this.createIssuerCipherParams(privKey); X509Certificate clientCert; Hashtable extension = new Hashtable(); extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier))); String completeRole = ""; for (String role : roles) { completeRole += role + ", "; } completeRole = completeRole.substring(0, completeRole.length() - 2); extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole))); extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider()))); Map<String, String> extensionMap = new HashMap(); if (id.getOtherValues() != null) { for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) { extension.put(new DERObjectIdentifier(entry.getKey().getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue()))); extensionMap.put(entry.getKey().getName(), entry.getValue()); } } try { String x509NameString = ""; x509NameString += "CN=" + id.getCommonName(); if (id.getSurname() != null && !id.getSurname().equals("")) { x509NameString += ", SURNAME=" + id.getSurname(); } if (id.getGivenName() != null && !id.getGivenName().equals("")) { x509NameString += ", GIVENNAME=" + id.getGivenName(); } if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) { x509NameString += ", UID=" + id.getUniqueIdentifier(); } if (id.getOrganisation() != null && !id.getOrganisation().equals("")) { x509NameString += ", O=" + id.getOrganisation(); } if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) { x509NameString += ", OU=" + id.getOrganisationUnit(); } if (id.getCountryName() != null && !id.getCountryName().equals("")) { x509NameString += ", C=" + id.getCountryName(); } if (id.getState() != null && !id.getState().equals("")) { x509NameString += ", ST=" + id.getState(); } if (id.getLocality() != null && !id.getLocality().equals("")) { x509NameString += ", L=" + id.getLocality(); } X509Name x509Name = new X509Name(x509NameString); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis()))); certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setSubject(x509Name); certGen.setExtensions(new X509Extensions(extension)); DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5"); AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull()); certGen.setSignature(sigAlgId); certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject())); certGen.setStartDate(new Time(new Date(System.currentTimeMillis()))); certGen.setEndDate(new Time(getExpiryDate(validity).getTime())); TBSCertificateStructure tbsCert = certGen.generateTBSCertificate(); //Sign certificate SHA1Digest digester = new SHA1Digest(); AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(tbsCert); byte[] signature; byte[] certBlock = bOut.toByteArray(); // first create digest digester.update(certBlock, 0, certBlock.length); byte[] hash = new byte[digester.getDigestSize()]; digester.doFinal(hash, 0); // then sign it rsa.init(true, cipherParams); DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash); byte[] digest = dInfo.getEncoded(ASN1Encodable.DER); signature = rsa.processBlock(digest, 0, digest.length); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgId); v.add(new DERBitString(signature)); // Create CRT data structure clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v))); clientCert.verify(caCert.getPublicKey()); } catch (IOException | InvalidCipherTextException | CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException e) { logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() }); throw new CertificateCreationException("230 Could not create client certificate"); } Certificate cert = new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap); //post message on UniBoard if corresponding JNDI parameter is defined postOnUniBoard(cert, uniBoardWsdlURL, uniBoardServiceURL, section, (RSAPublicKey) caCert.getPublicKey(), privKey); return cert; }
From source file:ch.bfh.unicert.issuer.CertificateIssuerBean.java
License:GNU General Public License
/** * Actually creates the requestor certificate. * * @param id requestor identity data/* w ww . j a v a2 s .co m*/ * @param caCert certificate of the certification authority * @param cipherParams issuer private key parameters used for signing * @param pk public key of the requestor to certify * @param expiry the expiry date * @param applicationIdentifier the application identifier for which te certificate is issued * @param role role for which the certificate is issued * @return the certificate object containing the X509 certificate * @throws CertificateCreationException if an error occurs */ private Certificate createClientCertificate(IdentityData id, X509Certificate caCert, CipherParameters cipherParams, PublicKey pk, Calendar expiry, String applicationIdentifier, String[] roles) throws CertificateCreationException { X509Certificate clientCert; Hashtable extension = new Hashtable(); extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier))); String completeRole = ""; for (String role : roles) { completeRole += role + ", "; } completeRole = completeRole.substring(0, completeRole.length() - 2); extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole))); extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider()))); Map<String, String> extensionMap = new HashMap(); if (id.getOtherValues() != null) { for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) { extension.put(new DERObjectIdentifier(entry.getKey().getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue()))); extensionMap.put(entry.getKey().getName(), entry.getValue()); } } try { String x509NameString = ""; x509NameString += "CN=" + id.getCommonName(); if (id.getSurname() != null && !id.getSurname().equals("")) { x509NameString += ", SURNAME=" + id.getSurname(); } if (id.getGivenName() != null && !id.getGivenName().equals("")) { x509NameString += ", GIVENNAME=" + id.getGivenName(); } if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) { x509NameString += ", UID=" + id.getUniqueIdentifier(); } if (id.getOrganisation() != null && !id.getOrganisation().equals("")) { x509NameString += ", O=" + id.getOrganisation(); } if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) { x509NameString += ", OU=" + id.getOrganisationUnit(); } if (id.getCountryName() != null && !id.getCountryName().equals("")) { x509NameString += ", C=" + id.getCountryName(); } if (id.getState() != null && !id.getState().equals("")) { x509NameString += ", ST=" + id.getState(); } if (id.getLocality() != null && !id.getLocality().equals("")) { x509NameString += ", L=" + id.getLocality(); } X509Name x509Name = new X509Name(x509NameString); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis()))); certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setSubject(x509Name); certGen.setExtensions(new X509Extensions(extension)); DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5"); AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull()); certGen.setSignature(sigAlgId); certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject())); certGen.setStartDate(new Time(new Date(System.currentTimeMillis()))); certGen.setEndDate(new Time(expiry.getTime())); TBSCertificateStructure tbsCert = certGen.generateTBSCertificate(); //Sign certificate SHA1Digest digester = new SHA1Digest(); AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(tbsCert); byte[] signature; byte[] certBlock = bOut.toByteArray(); // first create digest digester.update(certBlock, 0, certBlock.length); byte[] hash = new byte[digester.getDigestSize()]; digester.doFinal(hash, 0); // then sign it rsa.init(true, cipherParams); DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash); byte[] digest = dInfo.getEncoded(ASN1Encodable.DER); signature = rsa.processBlock(digest, 0, digest.length); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgId); v.add(new DERBitString(signature)); // Create CRT data structure clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v))); clientCert.verify(caCert.getPublicKey()); } catch (IOException | CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | InvalidCipherTextException | SignatureException e) { logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() }); throw new CertificateCreationException("230 Could not create client certificate"); } return new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap); }
From source file:com.itextpdf.text.pdf.TSAClientBouncyCastle.java
License:Open Source License
/** * Get timestamp token - Bouncy Castle request encoding / decoding layer *//* ww w. j a v a 2 s . c o m*/ protected byte[] getTimeStampToken(byte[] imprint) throws Exception { byte[] respBytes = null; try { // Setup the time stamp request TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.setCertReq(true); // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1"); BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); TimeStampRequest request = tsqGenerator.generate(X509ObjectIdentifiers.id_SHA1.getId(), imprint, nonce); byte[] requestBytes = request.getEncoded(); // Call the communications layer respBytes = getTSAResponse(requestBytes); // Handle the TSA response TimeStampResponse response = new TimeStampResponse(respBytes); // validate communication level attributes (RFC 3161 PKIStatus) response.validate(request); PKIFailureInfo failure = response.getFailInfo(); int value = (failure == null) ? 0 : failure.intValue(); if (value != 0) { // @todo: Translate value of 15 error codes defined by PKIFailureInfo to string throw new Exception(MessageLocalization.getComposedMessage("invalid.tsa.1.response.code.2", tsaURL, String.valueOf(value))); } // @todo: validate the time stap certificate chain (if we want // assure we do not sign using an invalid timestamp). // extract just the time stamp token (removes communication status info) TimeStampToken tsToken = response.getTimeStampToken(); if (tsToken == null) { throw new Exception(MessageLocalization.getComposedMessage( "tsa.1.failed.to.return.time.stamp.token.2", tsaURL, response.getStatusString())); } TimeStampTokenInfo info = tsToken.getTimeStampInfo(); // to view details byte[] encoded = tsToken.getEncoded(); long stop = System.currentTimeMillis(); // Update our token size estimate for the next call (padded to be safe) this.tokSzEstimate = encoded.length + 32; return encoded; } catch (Exception e) { throw e; } catch (Throwable t) { throw new Exception(MessageLocalization.getComposedMessage("failed.to.get.tsa.response.from.1", tsaURL), t); } }
From source file:com.spilowagie.text.pdf.TSAClientBouncyCastle.java
License:Mozilla Public License
/** * Get timestamp token - Bouncy Castle request encoding / decoding layer *//*from www. j av a 2 s.co m*/ protected byte[] getTimeStampToken(byte[] imprint) throws Exception { byte[] respBytes = null; try { // Setup the time stamp request TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.setCertReq(true); // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1"); BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); TimeStampRequest request = tsqGenerator.generate(X509ObjectIdentifiers.id_SHA1.getId(), imprint, nonce); byte[] requestBytes = request.getEncoded(); // Call the communications layer respBytes = getTSAResponse(requestBytes); // Handle the TSA response TimeStampResponse response = new TimeStampResponse(respBytes); // validate communication level attributes (RFC 3161 PKIStatus) response.validate(request); PKIFailureInfo failure = response.getFailInfo(); int value = (failure == null) ? 0 : failure.intValue(); if (value != 0) { // @todo: Translate value of 15 error codes defined by PKIFailureInfo to string throw new Exception("Invalid TSA '" + tsaURL + "' response, code " + value); } // @todo: validate the time stap certificate chain (if we want // assure we do not sign using an invalid timestamp). // extract just the time stamp token (removes communication status info) TimeStampToken tsToken = response.getTimeStampToken(); if (tsToken == null) { throw new Exception( "TSA '" + tsaURL + "' failed to return time stamp token: " + response.getStatusString()); } TimeStampTokenInfo info = tsToken.getTimeStampInfo(); // to view details byte[] encoded = tsToken.getEncoded(); long stop = System.currentTimeMillis(); // Update our token size estimate for the next call (padded to be safe) this.tokSzEstimate = encoded.length + 32; return encoded; } catch (Exception e) { throw e; } catch (Throwable t) { throw new Exception("Failed to get TSA response from '" + tsaURL + "'", t); } }
From source file:es.gob.afirma.signers.tsp.pkcs7.CMSTimestamper.java
License:Open Source License
/** Obtiene directamente el <i>token</i> de sello de tiempo según RFC3161. * @param imprint Huella digital de los datos sobre los que se quiere obtener el sello de tiempo * @param hashAlgorithm Algoritmo de huella digital usado para calcular la huella indicada en <code>imprint</code>. * @param time Tiempo de solicitud del sello. * @return <i>Token</i> de sello de tiempo según RFC3161. * @throws AOException Si se produce un error en el protocolo TSA o en ASN.1. * @throws IOException Si hay errores en la comunicación o en la lectura de datos con la TSA. */ public byte[] getTimeStampToken(final byte[] imprint, final String hashAlgorithm, final Calendar time) throws AOException, IOException { final TimeStampRequest request = this.tsqGenerator.generate( new ASN1ObjectIdentifier(hashAlgorithm != null ? AOAlgorithmID.getOID(hashAlgorithm) : X509ObjectIdentifiers.id_SHA1.getId()), imprint, BigInteger.valueOf(time != null ? time.getTimeInMillis() : System.currentTimeMillis())); final byte[] requestBytes = request.getEncoded(); final byte[] rawResponse = getTSAResponse(requestBytes); final TimeStampResponse response; try {// ww w. j a va 2 s. com response = new TimeStampResponse(rawResponse); } catch (final Exception e) { throw new AOException("Error obteniendo la respuesta de la TSA: " + e, e); //$NON-NLS-1$ } // Validamos los atributos de la respuesta (RFC 3161 PKIStatus) try { response.validate(request); } catch (final Exception e) { throw new AOException("Error validando la respuesta de la TSA: " + e, e); //$NON-NLS-1$ } final PKIFailureInfo failure = response.getFailInfo(); final int value = failure == null ? 0 : failure.intValue(); if (value != 0) { throw new AOException("Respuesta invalida de la TSA ('" + this.tsaURL + "') con el codigo " + value); //$NON-NLS-1$ //$NON-NLS-2$ } // Extraemos el token de sello de tiempo (quitando la informacion de estado de las comunicaciones) final TimeStampToken tsToken = response.getTimeStampToken(); if (tsToken == null) { throw new AOException("La respuesta de la TSA ('" + this.tsaURL + "') no es un sello de tiempo valido: " //$NON-NLS-1$//$NON-NLS-2$ + new String(rawResponse)); } return tsToken.getEncoded(); }
From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileC.java
License:Open Source License
/** * Create a reference to a X509Certificate * /* w w w. j av a2 s . co m*/ * @param cert * @return * @throws NoSuchAlgorithmException * @throws CertificateEncodingException */ private OtherCertID makeOtherCertID(X509Certificate cert) throws NoSuchAlgorithmException, CertificateEncodingException { MessageDigest sha1digest = MessageDigest.getInstance(X509ObjectIdentifiers.id_SHA1.getId(), new BouncyCastleProvider()); byte[] d = sha1digest.digest(cert.getEncoded()); LOG.info(new DEROctetString(d).getDERObject().toString()); OtherHash hash = new OtherHash(sha1digest.digest(cert.getEncoded())); OtherCertID othercertid = new OtherCertID(new DERSequence(hash.getDERObject())); return othercertid; }
From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileC.java
License:Open Source License
/** * Create a reference to a X509CRL/*from www.j av a2 s . co m*/ * * @param crl * @return * @throws NoSuchAlgorithmException * @throws CRLException */ private CrlValidatedID makeCrlValidatedID(X509CRL crl) throws NoSuchAlgorithmException, CRLException { MessageDigest sha1digest = MessageDigest.getInstance(X509ObjectIdentifiers.id_SHA1.getId(), new BouncyCastleProvider()); OtherHash hash = new OtherHash(sha1digest.digest(crl.getEncoded())); BigInteger crlnumber; CrlIdentifier crlid; if (crl.getExtensionValue("2.5.29.20") != null) { crlnumber = new DERInteger(crl.getExtensionValue("2.5.29.20")).getPositiveValue(); crlid = new CrlIdentifier(new X500Name(crl.getIssuerX500Principal().getName()), new DERUTCTime(crl.getThisUpdate()), crlnumber); } else { crlid = new CrlIdentifier(new X500Name(crl.getIssuerX500Principal().getName()), new DERUTCTime(crl.getThisUpdate())); } CrlValidatedID crlvid = new CrlValidatedID(hash, crlid); return crlvid; }
From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileC.java
License:Open Source License
/** * Create a reference on a OCSPResp//from ww w . j a v a2 s . c om * * @param ocspResp * @return * @throws NoSuchAlgorithmException * @throws OCSPException * @throws IOException */ private OcspResponsesID makeOcspResponsesID(BasicOCSPResp ocspResp) throws NoSuchAlgorithmException, OCSPException, IOException { /* * We hash the complete response, this is not clear in the TS but the issue was addressed here: * http://lists.iaik.tugraz.at/pipermail/jce-general/2007-January/005914.html */ MessageDigest sha1digest = MessageDigest.getInstance(X509ObjectIdentifiers.id_SHA1.getId(), new BouncyCastleProvider()); byte[] digestValue = sha1digest.digest(ocspResp.getEncoded()); OtherHash hash = new OtherHash(digestValue); OcspResponsesID ocsprespid = new OcspResponsesID(new OcspIdentifier( ocspResp.getResponderId().toASN1Object(), new DERGeneralizedTime(ocspResp.getProducedAt())), hash); LOG.info("Incorporate OcspResponseId[hash=" + Hex.encodeHexString(digestValue) + ",producedAt=" + ocspResp.getProducedAt()); return ocsprespid; }
From source file:eu.europa.ejusticeportal.dss.applet.model.token.CertificateDisplayUtils.java
License:EUPL
/** * Calculate a digest of the signing certificate. This is used to get a unique id for it. * //from w w w . j av a 2s .c om * @param cert the certificate to digest * @return the digest (SHA1, encoded as hex) */ public static String digest(X509Certificate cert) { String digest = null; try { MessageDigest sha1digest = MessageDigest.getInstance(X509ObjectIdentifiers.id_SHA1.getId(), new BouncyCastleProvider()); digest = Hex.encodeHexString(sha1digest.digest(cert.getEncoded())); } catch (Exception e) { ExceptionUtils.throwException(new UnexpectedException(e), LOG); } return digest; }
From source file:org.apache.poi.poifs.crypt.dsig.services.TSPTimeStampService.java
License:Apache License
/** * Maps the digest algorithm to corresponding OID value. *//*from w w w.ja va2 s . co m*/ public ASN1ObjectIdentifier mapDigestAlgoToOID(HashAlgorithm digestAlgo) { switch (digestAlgo) { case sha1: return X509ObjectIdentifiers.id_SHA1; case sha256: return NISTObjectIdentifiers.id_sha256; case sha384: return NISTObjectIdentifiers.id_sha384; case sha512: return NISTObjectIdentifiers.id_sha512; default: throw new IllegalArgumentException("unsupported digest algo: " + digestAlgo); } }