List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject
public ASN1Primitive readObject() throws IOException
From source file:org.dataone.proto.trove.jsse.X509CertificateToolset.java
License:Apache License
/** * Converts the byte data into a DERObject * * @see http://stackoverflow.com/questions/2409618/how-do-i-decode-a-der-encoded-string-in-java * @param data/*from w w w .ja v a 2 s .co m*/ * @return * @throws IOException */ private ASN1Primitive toASN1Primitive(byte[] data) throws IOException { ASN1Primitive dero = null; ASN1InputStream asnInputStream = null; try { ByteArrayInputStream inStream = new ByteArrayInputStream(data); asnInputStream = new ASN1InputStream(inStream); dero = asnInputStream.readObject(); } finally { IOUtils.closeQuietly(asnInputStream); } return dero; }
From source file:org.dcache.srm.client.GsiConnectionSocketFactory.java
License:Open Source License
private void delegate(Socket socket, HttpClientTransport.Delegation delegation, X509Credential credential) throws IOException { if (delegation != null) { switch (delegation) { case SKIP: break; case NONE: socket.getOutputStream().write('0'); socket.getOutputStream().flush(); break; case LIMITED: case FULL: socket.getOutputStream().write('D'); socket.getOutputStream().flush(); try { // read csr ASN1InputStream dIn = new ASN1InputStream(socket.getInputStream()); PKCS10CertificationRequest csr = new PKCS10CertificationRequest( CertificationRequest.getInstance(dIn.readObject())); // generate proxy ProxyRequestOptions options = new ProxyRequestOptions(credential.getCertificateChain(), csr); options.setLimited(delegation == HttpClientTransport.Delegation.LIMITED); X509Certificate[] chain = ProxyGenerator.generate(options, credential.getKey()); // send to server socket.getOutputStream().write(chain[0].getEncoded()); socket.getOutputStream().flush(); } catch (SignatureException | NoSuchProviderException | CertificateEncodingException | InvalidKeyException | NoSuchAlgorithmException | CertificateParsingException e) { throw new IOException("Failed to signed CSR during delegation: " + e.getMessage(), e); }// w w w . j av a 2 s .co m break; } } }
From source file:org.dcache.xrootd.plugins.authn.gsi.DHSession.java
License:Open Source License
/** * Creates an DHParameterSpec object from the DER-encoded byte sequence * @param der the DER-encoded byte sequence * @return the DHParameterSpec object// w ww . j a v a 2 s. co m * @throws IOException if the deserialisation goes wrong */ private static DHParameterSpec fromDER(byte[] der) throws IOException { ByteArrayInputStream inStream = new ByteArrayInputStream(der); ASN1InputStream derInputStream = new ASN1InputStream(inStream); DHParameter dhparam = DHParameter.getInstance(derInputStream.readObject()); return new DHParameterSpec(dhparam.getP(), dhparam.getG()); }
From source file:org.demoiselle.signer.policy.engine.factory.PolicyFactory.java
License:Open Source License
private ASN1Primitive readANS1FromStream(InputStream is) { ASN1InputStream asn1is = new ASN1InputStream(is); ASN1Primitive primitive = null;//from w w w . j av a 2 s . com try { primitive = asn1is.readObject(); } catch (IOException error) { LOGGER.getLevel(); LOGGER.log(Level.ERROR, "Error reading stream.", error); throw new RuntimeException(error); } finally { try { asn1is.close(); } catch (IOException error) { throw new RuntimeException(error); } } return primitive; }
From source file:org.dihedron.crypto.certificates.Certificates.java
License:Open Source License
/** * @param certificate /*from w w w . j a v a 2 s . c o m*/ * the certificate in which to look to the extension value. * @param oid * the Object Identifier of the extension. * @return * the extension value as an {@code ASN1Primitive} object. * @throws IOException */ public static ASN1Primitive getExtensionValue(X509Certificate certificate, String oid) throws IOException { byte[] bytes = certificate.getExtensionValue(oid); if (bytes == null) { return null; } ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(bytes)); ASN1OctetString octets = (ASN1OctetString) stream.readObject(); stream = new ASN1InputStream(new ByteArrayInputStream(octets.getOctets())); return stream.readObject(); }
From source file:org.ebayopensource.fido.uaf.crypto.Asn1.java
License:Apache License
/** * DER - From byte[] to Big Integer rs//from w ww .j ava 2 s .co m * UAF_ALG_SIGN_SECP256K1_ECDSA_SHA256_DER 0x06 DER [ITU-X690-2008] encoded * ECDSA signature [RFC5480] on the secp256k1 curve. I.e. a DER encoded * SEQUENCE { r INTEGER, s INTEGER } * * @param signature * @return * @throws IOException */ public static BigInteger[] decodeToBigIntegerArray(byte[] signature) throws IOException { ASN1InputStream decoder = new ASN1InputStream(signature); DLSequence seq = (DLSequence) decoder.readObject(); ASN1Integer r = (ASN1Integer) seq.getObjectAt(0); ASN1Integer s = (ASN1Integer) seq.getObjectAt(1); decoder.close(); BigInteger[] ret = new BigInteger[2]; ret[0] = r.getPositiveValue(); ret[1] = s.getPositiveValue(); return ret; }
From source file:org.eclipse.andmore.android.certmanager.core.KeyStoreUtils.java
License:Apache License
/** * Create a new X509 certificate for a given KeyPair * //ww w . ja va 2 s .co m * @param keyPair * the {@link KeyPair} used to create the certificate, * RSAPublicKey and RSAPrivateKey are mandatory on keyPair, * IllegalArgumentExeption will be thrown otherwise. * @param issuerName * The issuer name to be used on the certificate * @param ownerName * The owner name to be used on the certificate * @param expireDate * The expire date * @return The {@link X509Certificate} * @throws IOException * @throws OperatorCreationException * @throws CertificateException */ public static X509Certificate createX509Certificate(KeyPair keyPair, CertificateDetailsInfo certDetails) throws IOException, OperatorCreationException, CertificateException { PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); if (!(publicKey instanceof RSAPublicKey) || !(privateKey instanceof RSAPrivateKey)) { throw new IllegalArgumentException(CertificateManagerNLS.KeyStoreUtils_RSA_Keys_Expected); } RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey; // Transform the PublicKey into the BouncyCastle expected format ASN1InputStream asn1InputStream = null; X509Certificate x509Certificate = null; try { asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(rsaPublicKey.getEncoded())); SubjectPublicKeyInfo pubKey = new SubjectPublicKeyInfo((ASN1Sequence) asn1InputStream.readObject()); X500NameBuilder nameBuilder = new X500NameBuilder(new BCStrictStyle()); addField(BCStyle.C, certDetails.getCountry(), nameBuilder); addField(BCStyle.ST, certDetails.getState(), nameBuilder); addField(BCStyle.L, certDetails.getLocality(), nameBuilder); addField(BCStyle.O, certDetails.getOrganization(), nameBuilder); addField(BCStyle.OU, certDetails.getOrganizationUnit(), nameBuilder); addField(BCStyle.CN, certDetails.getCommonName(), nameBuilder); X500Name subjectName = nameBuilder.build(); X500Name issuerName = subjectName; X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerName, BigInteger.valueOf(new SecureRandom().nextInt()), Calendar.getInstance().getTime(), certDetails.getExpirationDate(), subjectName, pubKey); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); //$NON-NLS-1$ AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); BcContentSignerBuilder sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); // Create RSAKeyParameters, the private key format expected by // Bouncy Castle RSAKeyParameters keyParams = new RSAKeyParameters(true, rsaPrivateKey.getPrivateExponent(), rsaPrivateKey.getModulus()); ContentSigner contentSigner = sigGen.build(keyParams); X509CertificateHolder certificateHolder = certBuilder.build(contentSigner); // Convert the X509Certificate from BouncyCastle format to the // java.security format JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter(); x509Certificate = certConverter.getCertificate(certificateHolder); } finally { if (asn1InputStream != null) { try { asn1InputStream.close(); } catch (IOException e) { AndmoreLogger .error("Could not close stream while creating X509 certificate. " + e.getMessage()); } } } return x509Certificate; }
From source file:org.eclipse.andmore.android.certmanager.packaging.sign.SignatureBlockFile.java
License:Apache License
/** * Writes this file to an output stream// w w w . ja v a 2s . co m * * @param outputStream * the output stream to write the file * @throws IOException * if an I/O error occurs during the signing process * @throws SignException * if a processing error occurs during the signing process * @throws KeyStoreManagerException * @throws KeyStoreException * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws CertificateEncodingException * @throws OperatorCreationException * @throws CMSException */ public void write(OutputStream outputStream) throws IOException, SignException, UnrecoverableKeyException, KeyStoreException, KeyStoreManagerException, NoSuchAlgorithmException, InvalidKeyException, CertificateEncodingException, OperatorCreationException, CMSException { // get certificate from entry X509Certificate[] certChain = { keystoreEntry.getX509Certificate() }; if (certChain.length > 0) { X509Certificate publicKey = certChain[0]; PrivateKey privateKey = keystoreEntry.getPrivateKey(keyEntryPassword); String blockalgorithm = getBlockAlgorithm(); if (!blockalgorithm.equalsIgnoreCase(ISignConstants.DSA) && !blockalgorithm.equalsIgnoreCase(ISignConstants.RSA)) { AndmoreLogger.error(SignatureBlockFile.class, "Signing block algorithm not supported. Key algorithm must be DSA or RSA"); throw new SignException("Signing block algorithm not supported"); } String signatureAlgorithm = ISignConstants.SHA1 + ISignConstants.ALGORITHM_CONNECTOR + blockalgorithm; Security.addProvider(new BouncyCastleProvider()); ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(publicKey); JcaCertStore certs = new JcaCertStore(certList); ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); generator.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()) .setDirectSignature(true).build(signer, publicKey)); generator.addCertificates(certs); ByteArrayOutputStream baos = new ByteArrayOutputStream(); signatureFile.write(baos); CMSTypedData cmsdata = new CMSProcessableByteArray(baos.toByteArray()); CMSSignedData signeddata = generator.generate(cmsdata, false); ASN1InputStream asn1 = new ASN1InputStream(signeddata.getEncoded()); DEROutputStream dos = new DEROutputStream(outputStream); dos.writeObject(asn1.readObject()); dos.flush(); dos.close(); asn1.close(); } AndmoreLogger.info(SignatureBlockFile.class, "Created signature block file"); }
From source file:org.ejbca.core.ejb.authentication.web.WebAuthenticationProviderSessionBeanTest.java
License:Open Source License
private static X509Certificate generateUnbornCert(String dn, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, IllegalStateException, NoSuchProviderException, OperatorCreationException, CertificateException, IOException { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; // Create self signed certificate Date firstDate = new Date(); // Set starting date to tomorrow firstDate.setTime(firstDate.getTime() + (24 * 3600 * 1000)); Date lastDate = new Date(); // Set Expiry in two days lastDate.setTime(lastDate.getTime() + ((2 * 24 * 60 * 60 * 1000))); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;/*ww w .j a v a 2 s. c o m*/ if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { publicKey = pubKey; } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (InvalidKeySpecException e) { publicKey = pubKey; } catch (NullPointerException e) { publicKey = pubKey; } } else { publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(CertTools.stringToBcX500Name(dn), new java.math.BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn), pkinfo); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certbuilder.addExtension(Extension.basicConstraints, true, bc); // Put critical KeyUsage in CA-certificates if (isCA) { X509KeyUsage ku = new X509KeyUsage(keyusage); certbuilder.addExtension(Extension.keyUsage, true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { ASN1InputStream spkiAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); ASN1InputStream apkiAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); try { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) spkiAsn1InputStream.readObject()); X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils(); SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) apkiAsn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki); } finally { spkiAsn1InputStream.close(); apkiAsn1InputStream.close(); } } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certbuilder.addExtension(Extension.certificatePolicies, false, seq); } final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); return selfcert; }
From source file:org.ejbca.core.ejb.ca.crl.CreateCRLSessionTest.java
License:Open Source License
/** * Tests the extension CRL Distribution Point on CRLs * /*from ww w. java 2 s . co m*/ * @throws Exception * error */ public void test06CRLDistPointOnCRL() throws Exception { log.trace(">test06CRLDistPointOnCRL()"); final String cdpURL = "http://www.ejbca.org/foo/bar.crl"; X509CAInfo cainfo = (X509CAInfo) ca.getCAInfo(); X509CRL x509crl; byte[] cdpDER; cainfo.setUseCrlDistributionPointOnCrl(true); cainfo.setDefaultCRLDistPoint(cdpURL); caAdminSession.editCA(admin, cainfo); ca = caSession.getCA(admin, caid); crlCreateSession.run(admin, ca); x509crl = CertTools.getCRLfromByteArray(crlSession.getLastCRL(admin, cainfo.getSubjectDN(), false)); cdpDER = x509crl.getExtensionValue(X509Extensions.IssuingDistributionPoint.getId()); assertNotNull("CRL has no distribution points", cdpDER); ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(cdpDER)); ASN1OctetString octs = (ASN1OctetString) aIn.readObject(); aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets())); IssuingDistributionPoint cdp = new IssuingDistributionPoint((ASN1Sequence) aIn.readObject()); DistributionPointName distpoint = cdp.getDistributionPoint(); assertEquals("CRL distribution point is different", cdpURL, ((DERIA5String) ((GeneralNames) distpoint.getName()).getNames()[0].getName()).getString()); cainfo.setUseCrlDistributionPointOnCrl(false); cainfo.setDefaultCRLDistPoint(""); caAdminSession.editCA(admin, cainfo); ca = caSession.getCA(admin, caid); crlCreateSession.run(admin, ca); x509crl = CertTools.getCRLfromByteArray(crlSession.getLastCRL(admin, cainfo.getSubjectDN(), false)); assertNull("CRL has distribution points", x509crl.getExtensionValue(X509Extensions.CRLDistributionPoints.getId())); log.trace("<test06CRLDistPointOnCRL()"); }