List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject
public ASN1Primitive readObject() throws IOException
From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectBuilderTest.java
License:BSD License
/** * http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.1.2 */// ww w.java 2 s. c o m @Test public void shouldCmsObjectHaveCorrectDigestAlgorithm() throws Exception { ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(cmsObject.getEncoded())); ContentInfo info = ContentInfo.getInstance(in.readObject()); SignedData signedData = SignedData.getInstance(info.getContent()); ASN1Set digestAlgorithms = signedData.getDigestAlgorithms(); ASN1Encodable asn1Object = digestAlgorithms.getObjectAt(0); AlgorithmIdentifier algorithmId = AlgorithmIdentifier.getInstance(asn1Object.toASN1Primitive()); assertEquals(DIGEST_SHA256, algorithmId.getAlgorithm().getId()); }
From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectParser.java
License:BSD License
private AlgorithmIdentifier getDigestAlgorithmOidFromEncodedCmsObject(byte[] data) { ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(data)); ContentInfo info;/*from w w w.ja v a 2 s. co m*/ try { info = ContentInfo.getInstance(in.readObject()); } catch (IOException e) { throw new ProvisioningCmsObjectParserException("error while reading cms object content info", e); } SignedData signedData = SignedData.getInstance(info.getContent()); ASN1Set digestAlgorithms = signedData.getDigestAlgorithms(); ASN1Encodable object = digestAlgorithms.getObjectAt(0); return AlgorithmIdentifier.getInstance(object.toASN1Primitive()); }
From source file:net.sabamiso.android.revocationtest.crl.RevocationTestUsingCRL.java
License:MIT License
private static CRLDistPoint getCRLDistPoint(byte[] asn1_bytes) { if (asn1_bytes == null) return null; CRLDistPoint crldp = null;// w w w. jav a2 s . c o m try { ASN1InputStream is1 = new ASN1InputStream(new ByteArrayInputStream(asn1_bytes)); ASN1Primitive p1 = is1.readObject(); if (p1 == null) return null; ASN1InputStream is2 = new ASN1InputStream(ASN1OctetString.getInstance(p1).getOctets()); ASN1Primitive p2 = is2.readObject(); if (p2 == null) return null; crldp = CRLDistPoint.getInstance(p2); } catch (IOException e) { e.printStackTrace(); } return crldp; }
From source file:net.sf.assinafacil.UtiICPBrasill.java
License:Open Source License
/** * Interpreta um dado do tipo otherName. * Obs. O JDK 5.0 no tem classes que lidem com um dado do tipo OtherName. * necessrio usar o BouncyCastle. //from w w w . j ava 2 s.c o m * @param encoded O dado em ASN.1. * @return Um par contendo o OID e o contedo. */ private static Pair<DERObjectIdentifier, String> getOtherName(byte[] encoded) throws IOException { // O JDK 5.0 no tem classes que lidem com um dado do tipo OtherName. // necessrio usar o BouncyCastle. ASN1InputStream inps = new ASN1InputStream(encoded); DERSequence seq = null; DERObjectIdentifier oid = null; String conteudo = ""; seq = (DERSequence) inps.readObject(); inps.close(); Enumeration en = seq.getObjects(); oid = (DERObjectIdentifier) en.nextElement(); DERObject obj = ((ASN1TaggedObject) ((ASN1TaggedObject) en.nextElement()).getObject()).getObject(); if (obj instanceof DERString) { // Certificados antigos SERASA - incorretos conteudo = ((DERString) obj).getString(); } else if (obj instanceof DEROctetString) { // Certificados corretos conteudo = new String(((DEROctetString) obj).getOctets(), "ISO-8859-1"); } return new Pair<DERObjectIdentifier, String>(oid, conteudo); }
From source file:net.sf.assinafacil.UtiICPBrasill.java
License:Open Source License
public static Vector getCrlDistributionPoint(X509Certificate certificate) throws CertificateParsingException { try {//from w w w. j ava 2 s. c o m // ---- alternative code ---------- byte[] val1 = certificate.getExtensionValue("2.5.29.31"); if (val1 == null) { return new Vector(); } ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1)); DERObject derObj = oAsnInStream.readObject(); DEROctetString dos = (DEROctetString) derObj; byte[] val2 = dos.getOctets(); ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2)); DERObject derObj2 = oAsnInStream2.readObject(); Vector urls = getDERValue(derObj2); return urls; } catch (Exception e) { e.printStackTrace(); throw new CertificateParsingException(e.toString()); } }
From source file:net.sf.dsig.verify.OCSPHelper.java
License:Apache License
/** * Retrieve the OCSP URI distribution point from an X.509 certificate, using * the 1.3.6.1.5.5.7.1.1 extension value * /* www.j a va 2 s. c o m*/ * @param certificate the {@link X509Certificate} object * @return a String containing the URI of the OCSP authority info access, * or null if none can be found */ public static String getOCSPAccessLocationUri(X509Certificate certificate) { try { byte[] derAiaBytes = certificate.getExtensionValue(OID_AUTHORITYINFOACCESS); if (derAiaBytes == null) { return null; } ASN1InputStream ais = new ASN1InputStream(derAiaBytes); DEROctetString dos = (DEROctetString) ais.readObject(); ais.close(); ais = new ASN1InputStream(dos.getOctets()); DERSequence seq = (DERSequence) ais.readObject(); ais.close(); AuthorityInformationAccess aia = AuthorityInformationAccess.getInstance(seq); for (int i = 0; i < aia.getAccessDescriptions().length; i++) { AccessDescription ad = aia.getAccessDescriptions()[i]; if (!ad.getAccessMethod().equals(AccessDescription.id_ad_ocsp)) { continue; } GeneralName gn = ad.getAccessLocation(); if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) { return ((DERString) gn.getName()).getString(); } } } catch (IOException e) { logger.warn("ASN.1 decoding failed; will fall back to default OCSP AccessLocation, if set"); } return null; }
From source file:net.sf.dsig.verify.X509CRLHelper.java
License:Apache License
/** * Retrieve the CRL URI distribution point from an X.509 certificate, using * the 2.5.29.31 extension value// ww w . jav a2s.c o m * * @param certificate an {@link X509Certificate} object * @return a String containing the URI of the CRL distribution point, or * null if none can be found */ public static String getCRLDistributionPointUri(X509Certificate certificate) { byte[] derCdpBytes = certificate.getExtensionValue(OID_CRLDISTRIBUTIONPOINTS); if (derCdpBytes == null) { return null; } try { ASN1InputStream ais = new ASN1InputStream(derCdpBytes); DEROctetString dos = (DEROctetString) ais.readObject(); ais.close(); ais = new ASN1InputStream(dos.getOctets()); DERSequence seq = (DERSequence) ais.readObject(); ais.close(); CRLDistPoint cdp = new CRLDistPoint(seq); for (int i = 0; i < cdp.getDistributionPoints().length; i++) { DistributionPoint dp = cdp.getDistributionPoints()[i]; DistributionPointName dpn = dp.getDistributionPoint(); GeneralNames gns = (GeneralNames) dpn.getName(); for (int j = 0; j < gns.getNames().length; j++) { GeneralName gn = gns.getNames()[j]; if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) { return ((DERString) gn.getName()).getString(); } } } } catch (IOException e) { logger.warn("ASN.1 decoding failed; will fall back to default CRL DistributionPoint, if set"); } return null; }
From source file:net.sf.jsignpdf.verify.VerifierLogic.java
License:Mozilla Public License
/** * Validates certificate (chain) using OCSP. * // w w w .j a v a 2s . c o m * @param pkc * certificate chain, 1st certificate will be validated * @param url * OCSP url for validation * @return */ private static boolean validateCertificateOCSP(Certificate pkc[], String url) { if (pkc.length < 2) { return false; } try { X509Certificate sigcer = (X509Certificate) pkc[0]; X509Certificate isscer = (X509Certificate) pkc[1]; OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle(sigcer, isscer, url); // TODO implement proxy support // ocspClient.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888))); byte[] encoded = ocspClient.getEncoded(); ASN1InputStream inp = new ASN1InputStream(encoded); BasicOCSPResponse resp = BasicOCSPResponse.getInstance(inp.readObject()); org.bouncycastle.ocsp.BasicOCSPResp basicResp = new org.bouncycastle.ocsp.BasicOCSPResp(resp); SingleResp sr = basicResp.getResponses()[0]; CertificateID cid = sr.getCertID(); CertificateID tis = new CertificateID(CertificateID.HASH_SHA1, isscer, sigcer.getSerialNumber()); return tis.equals(cid); } catch (Exception e) { return false; } }
From source file:net.sf.keystore_explorer.crypto.privatekey.OpenSslPvkUtil.java
License:Open Source License
/** * Load an unencrypted OpenSSL private key from the stream. The encoding of * the private key may be PEM or DER.//from w w w. j a va2 s . c o m * * @param is * Stream to load the unencrypted private key from * @return The private key * @throws PrivateKeyEncryptedException * If private key is encrypted * @throws CryptoException * Problem encountered while loading the private key * @throws IOException * An I/O error occurred */ public static PrivateKey load(InputStream is) throws CryptoException, IOException { byte[] streamContents = ReadUtil.readFully(is); EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents)); if (encType == null) { throw new CryptoException(res.getString("NotValidOpenSsl.exception.message")); } if (encType == ENCRYPTED) { throw new PrivateKeyEncryptedException(res.getString("OpenSslIsEncrypted.exception.message")); } // Check if stream is PEM encoded PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents)); if (pemInfo != null) { // It is - get DER from PEM streamContents = pemInfo.getContent(); } try { // Read OpenSSL der structure ASN1InputStream asn1InputStream = new ASN1InputStream(streamContents); ASN1Primitive openSsl = asn1InputStream.readObject(); asn1InputStream.close(); if (openSsl instanceof ASN1Sequence) { ASN1Sequence sequence = (ASN1Sequence) openSsl; for (int i = 0; i < sequence.size(); i++) { ASN1Encodable obj = sequence.getObjectAt(i); if (!(obj instanceof ASN1Integer)) { throw new CryptoException( res.getString("OpenSslSequenceContainsNonIntegers.exception.message")); } } if (sequence.size() == 9) { // RSA private key BigInteger version = ((ASN1Integer) sequence.getObjectAt(0)).getValue(); BigInteger modulus = ((ASN1Integer) sequence.getObjectAt(1)).getValue(); BigInteger publicExponent = ((ASN1Integer) sequence.getObjectAt(2)).getValue(); BigInteger privateExponent = ((ASN1Integer) sequence.getObjectAt(3)).getValue(); BigInteger primeP = ((ASN1Integer) sequence.getObjectAt(4)).getValue(); BigInteger primeQ = ((ASN1Integer) sequence.getObjectAt(5)).getValue(); BigInteger primeExponentP = ((ASN1Integer) sequence.getObjectAt(6)).getValue(); BigInteger primeExponenetQ = ((ASN1Integer) sequence.getObjectAt(7)).getValue(); BigInteger crtCoefficient = ((ASN1Integer) sequence.getObjectAt(8)).getValue(); if (!version.equals(VERSION)) { throw new CryptoException( MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue())); } RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponenetQ, crtCoefficient); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(rsaPrivateCrtKeySpec); } else if (sequence.size() == 6) { // DSA private key BigInteger version = ((ASN1Integer) sequence.getObjectAt(0)).getValue(); BigInteger primeModulusP = ((ASN1Integer) sequence.getObjectAt(1)).getValue(); BigInteger primeQ = ((ASN1Integer) sequence.getObjectAt(2)).getValue(); BigInteger generatorG = ((ASN1Integer) sequence.getObjectAt(3)).getValue(); /* publicExponentY not req for pvk */sequence.getObjectAt(4); BigInteger secretExponentX = ((ASN1Integer) sequence.getObjectAt(5)).getValue(); if (!version.equals(VERSION)) { throw new CryptoException( MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue())); } DSAPrivateKeySpec dsaPrivateKeySpec = new DSAPrivateKeySpec(secretExponentX, primeModulusP, primeQ, generatorG); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); return keyFactory.generatePrivate(dsaPrivateKeySpec); } else { throw new CryptoException(MessageFormat.format( res.getString("OpenSslSequenceIncorrectSize.exception.message"), "" + sequence.size())); } } else { throw new CryptoException(res.getString("OpenSslSequenceNotFound.exception.message")); } } catch (GeneralSecurityException ex) { throw new CryptoException(res.getString("NoLoadOpenSslPrivateKey.exception.message"), ex); } }
From source file:net.sf.keystore_explorer.crypto.privatekey.Pkcs8Util.java
License:Open Source License
private static String getPrivateKeyAlgorithm(byte[] unencPkcs8) throws IOException, CryptoException { // @formatter:off /*//from w ww. j ava 2 s . c om * Get private key algorithm from unencrypted PKCS #8 bytes: * * PrivateKeyInfo ::= ASN1Sequence { version Version, * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, privateKey * PrivateKey, attributes [0] IMPLICIT Attributes OPTIONAL } * * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier * * AlgorithmIdentifier ::= ASN1Sequence { algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL } */ // @formatter:on ASN1InputStream ais = null; try { ais = new ASN1InputStream(new ByteArrayInputStream(unencPkcs8)); ASN1Encodable derEnc; try { derEnc = ais.readObject(); } catch (OutOfMemoryError err) // Happens with some non ASN.1 files { throw new CryptoException(res.getString("NoUnencryptedPkcs8.exception.message")); } if (!(derEnc instanceof ASN1Sequence)) { throw new CryptoException(res.getString("NoUnencryptedPkcs8.exception.message")); } ASN1Sequence privateKeyInfoSequence = (ASN1Sequence) derEnc; derEnc = privateKeyInfoSequence.getObjectAt(1); if (!(derEnc instanceof ASN1Sequence)) { throw new CryptoException(res.getString("NoUnencryptedPkcs8.exception.message")); } ASN1Sequence privateKeyAlgorithmSequence = (ASN1Sequence) derEnc; derEnc = privateKeyAlgorithmSequence.getObjectAt(0); if (!(derEnc instanceof ASN1ObjectIdentifier)) { throw new CryptoException(res.getString("NoUnencryptedPkcs8.exception.message")); } ASN1ObjectIdentifier algorithmOid = (ASN1ObjectIdentifier) derEnc; String oid = algorithmOid.getId(); if (oid.equals(RSA.oid())) { return RSA.jce(); } else if (oid.equals(DSA.oid())) { return DSA.jce(); } else { return oid; // Unknown algorithm } } finally { IOUtils.closeQuietly(ais); } }