Example usage for org.bouncycastle.asn1 ASN1Primitive getEncoded

List of usage examples for org.bouncycastle.asn1 ASN1Primitive getEncoded

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1Primitive getEncoded.

Prototype

public byte[] getEncoded() throws IOException 

Source Link

Document

Return the default BER or DER encoding for this object.

Usage

From source file:com.itextpdf.signatures.LtvVerification.java

License:Open Source License

private PdfName getSignatureHashKey(String signatureName) throws NoSuchAlgorithmException, IOException {
    PdfDictionary dic = sgnUtil.getSignatureDictionary(signatureName);
    PdfString contents = dic.getAsString(PdfName.Contents);
    byte[] bc = PdfEncodings.convertToBytes(contents.getValue(), null);
    byte[] bt = null;
    if (PdfName.ETSI_RFC3161.equals(dic.getAsName(PdfName.SubFilter))) {
        ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(bc));
        ASN1Primitive pkcs = din.readObject();
        bc = pkcs.getEncoded();
    }//from  w  w  w.j  a  v a2s.  co m
    bt = hashBytesSha1(bc);
    return new PdfName(convertToHex(bt));
}

From source file:com.itextpdf.text.pdf.security.LtvVerification.java

License:Open Source License

private PdfName getSignatureHashKey(String signatureName) throws NoSuchAlgorithmException, IOException {
    PdfDictionary dic = acroFields.getSignatureDictionary(signatureName);
    PdfString contents = dic.getAsString(PdfName.CONTENTS);
    byte[] bc = contents.getOriginalBytes();
    byte[] bt = null;
    if (PdfName.ETSI_RFC3161.equals(PdfReader.getPdfObject(dic.get(PdfName.SUBFILTER)))) {
        ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(bc));
        ASN1Primitive pkcs = din.readObject();
        bc = pkcs.getEncoded();
    }//from  w  w  w  . j av  a  2s . com
    bt = hashBytesSha1(bc);
    return new PdfName(Utilities.convertToHex(bt));
}

From source file:net.sf.keystore_explorer.utilities.asn1.Asn1Dump.java

License:Open Source License

/**
 * Get dump of the supplied DER encoded ASN.1 object.
 *
 * @param der/*from  ww w  . j a  v  a2  s  .  c o  m*/
 *            DER encoded ASN.1 object
 * @return Dump of object
 * @throws Asn1Exception
 *             A problem was encountered getting the ASN.1 dump
 * @throws IOException
 *             If an I/O problem occurred
 */
public String dump(byte[] der) throws Asn1Exception, IOException {
    try {
        ASN1Primitive derObject = ASN1Primitive.fromByteArray(der);

        // if size of re-encoded DER primitive differs from input data there must be sth wrong
        if (derObject.getEncoded().length < der.length) {
            throw new Asn1Exception(res.getString("NoAsn1DumpObject.exception.message"));
        }

        return dump(derObject);
    } catch (IOException ex) {
        throw new Asn1Exception(res.getString("NoAsn1DumpObject.exception.message"), ex);
    }
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

License:Open Source License

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName, String path, String storepass, KeyStore store)
        throws KeystoreEditorException {
    OutputStream fos = null;//from   w  ww. ja  va  2s.  c om
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }
        Path storeFile = Paths.get(path);
        //check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            //priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            //java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();

            //we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();

                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }

            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //need to parse der separately from pem, der has the same mime type but is binary hence checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(
                                jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }

                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    Certificate certificate = certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate)
                            .getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(),
                                    keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(),
                                    chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.info(
                                    "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.",
                                    e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.info("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}

From source file:pro.javacard.gp.GlobalPlatform.java

License:Open Source License

private void parse_select_response(byte[] fci) throws GPException {
    try (ASN1InputStream ais = new ASN1InputStream(fci)) {
        if (ais.available() > 0) {
            // Read FCI
            DERApplicationSpecific fcidata = (DERApplicationSpecific) ais.readObject();
            // FIXME System.out.println(ASN1Dump.dumpAsString(fcidata, true));
            if (fcidata.getApplicationTag() == 15) {
                ASN1Sequence s = ASN1Sequence.getInstance(fcidata.getObject(BERTags.SEQUENCE));
                for (ASN1Encodable e : Lists.newArrayList(s.iterator())) {
                    ASN1TaggedObject t = DERTaggedObject.getInstance(e);
                    if (t.getTagNo() == 4) {
                        // ISD AID
                        ASN1OctetString isdaid = DEROctetString.getInstance(t.getObject());
                        AID detectedAID = new AID(isdaid.getOctets());
                        if (sdAID == null) {
                            logger.debug("Auto-detected ISD AID: " + detectedAID);
                        }//from  www . j a va  2  s  .c o  m
                        if (sdAID != null && !detectedAID.equals(sdAID)) {
                            giveStrictWarning("SD AID in FCI does not match the requested AID!");
                        }
                        this.sdAID = sdAID == null ? detectedAID : sdAID;
                    } else if (t.getTagNo() == 5) {
                        // Proprietary, usually a sequence
                        if (t.getObject() instanceof ASN1Sequence) {
                            ASN1Sequence prop = ASN1Sequence.getInstance(t.getObject());
                            for (ASN1Encodable enc : Lists.newArrayList(prop.iterator())) {
                                ASN1Primitive proptag = enc.toASN1Primitive();
                                if (proptag instanceof DERApplicationSpecific) {
                                    DERApplicationSpecific isddata = (DERApplicationSpecific) proptag;
                                    if (isddata.getApplicationTag() == 19) {
                                        spec = GPData.get_version_from_card_data(isddata.getEncoded());
                                        logger.debug("Auto-detected GP version: " + spec);
                                    }
                                } else if (proptag instanceof DERTaggedObject) {
                                    DERTaggedObject tag = (DERTaggedObject) proptag;
                                    if (tag.getTagNo() == 101) {
                                        setBlockSize(DEROctetString.getInstance(tag.getObject()));
                                    } else if (tag.getTagNo() == 110) {
                                        logger.debug("Lifecycle data (ignored): "
                                                + HexUtils.bin2hex(tag.getObject().getEncoded()));
                                    } else {
                                        logger.info("Unknown/unhandled tag in FCI proprietary data: "
                                                + HexUtils.bin2hex(tag.getEncoded()));
                                    }
                                } else {
                                    throw new GPException("Unknown data from card: "
                                            + HexUtils.bin2hex(proptag.getEncoded()));
                                }
                            }
                        } else {
                            // Except Feitian cards which have a plain nested tag
                            if (t.getObject() instanceof DERTaggedObject) {
                                DERTaggedObject tag = (DERTaggedObject) t.getObject();
                                if (tag.getTagNo() == 101) {
                                    setBlockSize(DEROctetString.getInstance(tag.getObject()));
                                } else {
                                    logger.info("Unknown/unhandled tag in FCI proprietary data: "
                                            + HexUtils.bin2hex(tag.getEncoded()));
                                }
                            }
                        }
                    } else {
                        logger.info("Unknown/unhandled tag in FCI: " + HexUtils.bin2hex(t.getEncoded()));
                    }
                }
            } else {
                throw new GPException("Unknown data from card: " + HexUtils.bin2hex(fci));
            }
        }
    } catch (IOException | ClassCastException e) {
        throw new GPException("Invalid data: " + e.getMessage(), e);
    }

}

From source file:support.revocation.OCSP.java

License:Apache License

/**
 * Processes the given OCSP response for a certificate that was issued by
 * the issuer which the given issuer certificate is issued for
 * @return the parsed OCSP result//from   w w  w .  jav  a 2  s .  c o m
 * @param response
 * @param issuerCertificate
 * @throws IOException
 * @throws GeneralSecurityException
 */
private static Response processOCSPResponse(OCSPResponse response, X509Certificate issuerCertificate)
        throws IOException, GeneralSecurityException {
    CertificateFactory factory = CertificateFactory.getInstance("X.509");

    try {
        if (response.getResponseBytes() == null)
            return new Response(false, null);

        // create basic response object
        BasicOCSPResponse basicResponse = BasicOCSPResponse
                .getInstance(parseASN1(response.getResponseBytes().getResponse()));

        // create signature object
        // is creating signatures from OIDs a well-defined process?
        String algorithm = basicResponse.getSignatureAlgorithm().getAlgorithm().getId();
        Signature signature = Signature.getInstance(algorithm);

        // set signature algorithm parameters
        ASN1Encodable encodableParams = basicResponse.getSignatureAlgorithm().getParameters();
        if (encodableParams != null && !encodableParams.equals(org.bouncycastle.asn1.DERNull.INSTANCE)) {

            ASN1Primitive primitiveParams = encodableParams.toASN1Primitive();
            if (primitiveParams != null && !primitiveParams.equals(org.bouncycastle.asn1.DERNull.INSTANCE)) {

                AlgorithmParameters params = AlgorithmParameters.getInstance(algorithm);
                params.init(primitiveParams.getEncoded());

                signature.setParameter(params.getParameterSpec(AlgorithmParameterSpec.class));
            }
        }

        // validate and use the certificate supplied by the OCSP response
        // where necessary
        ASN1Sequence certs = basicResponse.getCerts();
        if (certs != null && !certs.equals(org.bouncycastle.asn1.DERNull.INSTANCE)) {

            List<X509Certificate> certList = new ArrayList<>();
            for (int i = 0; i < certs.size(); i++) {
                X509Certificate cert = (X509Certificate) factory.generateCertificate(
                        new ByteArrayInputStream(certs.getObjectAt(0).toASN1Primitive().getEncoded()));
                cert.checkValidity();
                certList.add(cert);
            }

            CertPath path = factory.generateCertPath(certList);
            PKIXParameters params = new PKIXParameters(
                    Collections.singleton(new TrustAnchor(issuerCertificate, null)));
            params.setRevocationEnabled(false);
            CertPathValidator validator = CertPathValidator.getInstance("PKIX");
            PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(path, params);

            if (result.getTrustAnchor().getTrustedCert() == null)
                throw new CertPathValidatorException(
                        "Validation failed for certificate supplied by OCSP response", null, path, -1,
                        PKIXReason.NO_TRUST_ANCHOR);

            issuerCertificate = certList.get(0);
        }

        // verify OCSP response signature
        signature.initVerify(issuerCertificate.getPublicKey());
        signature.update(basicResponse.getTbsResponseData().getEncoded());
        if (!signature.verify(basicResponse.getSignature().getBytes()))
            throw new SignatureException("OCSP signature verification failed");

        // process response
        ASN1Sequence responses = basicResponse.getTbsResponseData().getResponses();
        if (responses.size() != 1)
            throw new GeneralSecurityException("OCSP response mismatch");
        SingleResponse singleResponse = SingleResponse.getInstance(responses.getObjectAt(0));

        // single response choices
        //   good        [0]     IMPLICIT NULL
        //   revoked     [1]     IMPLICIT RevokedInfo
        //   unknown     [2]     IMPLICIT UnknownInfo
        return new Response(singleResponse.getCertStatus().getTagNo() == 1,
                singleResponse.getNextUpdate() != null ? singleResponse.getNextUpdate().getDate() : null);
    } catch (ClassCastException | IllegalArgumentException | ParseException e) {
        throw new IOException(e);
    }
}

From source file:test.unit.org.owasp.webscarab.util.SunCertificateUtilsTest.java

License:Open Source License

@Test
public void testSign() throws Exception {
    // setup/*from www  .jav  a 2s.c om*/
    KeyPair caKeyPair = generateKeyPair();
    KeyPair entityKeyPair = generateKeyPair();
    X500Principal subject = new X500Principal("CN=Test");
    PublicKey pubKey = entityKeyPair.getPublic();
    X500Principal issuer = new X500Principal("CN=CA");
    PublicKey caPubKey = caKeyPair.getPublic();
    PrivateKey caKey = caKeyPair.getPrivate();
    Date begin = new Date();
    Date ends = new Date(begin.getTime() + (long) 1000 * 60 * 60 * 24 * 30);
    BigInteger serialNo = BigInteger.valueOf(1234);
    JcaX509ExtensionUtils jxeu = new JcaX509ExtensionUtils();

    // operate
    X509Certificate resultCert = SunCertificateUtils.sign(subject, pubKey, issuer, caPubKey, caKey, begin, ends,
            serialNo, null);

    // verify
    assertNotNull(resultCert);
    LOG.debug("result certificate: " + resultCert);
    resultCert.verify(caPubKey);
    assertEquals(subject, resultCert.getSubjectX500Principal());
    assertEquals(issuer, resultCert.getIssuerX500Principal());
    assertEquals(serialNo, resultCert.getSerialNumber());
    assertEquals(pubKey, resultCert.getPublicKey());
    LOG.debug("expected begin: " + begin.getTime());
    LOG.debug("actual begin: " + resultCert.getNotBefore().getTime());
    /*
     * BouncyCastle drops the milliseconds.
     */
    assertTrue(Math.abs(begin.getTime() - resultCert.getNotBefore().getTime()) < 1000);
    assertTrue(Math.abs(ends.getTime() - resultCert.getNotAfter().getTime()) < 1000);

    byte[] subjectKeyIdentifierExtValue = resultCert
            .getExtensionValue(X509Extension.subjectKeyIdentifier.getId());
    assertNotNull(subjectKeyIdentifierExtValue);
    ASN1Primitive subjectKeyIdentifier = JcaX509ExtensionUtils
            .parseExtensionValue(subjectKeyIdentifierExtValue);
    ASN1Primitive expSKI = jxeu.createSubjectKeyIdentifier(pubKey).toASN1Primitive();
    assertArrayEquals(expSKI.getEncoded(), subjectKeyIdentifier.getEncoded());

    byte[] authorityKeyIdentifierExtValue = resultCert
            .getExtensionValue(X509Extension.authorityKeyIdentifier.getId());
    ASN1Primitive authorityKeyIdentifier = JcaX509ExtensionUtils
            .parseExtensionValue(authorityKeyIdentifierExtValue);
    ASN1Primitive expAKI = jxeu.createAuthorityKeyIdentifier(caPubKey).toASN1Primitive();
    assertArrayEquals(expAKI.getEncoded(), authorityKeyIdentifier.getEncoded());

    assertEquals(-1, resultCert.getBasicConstraints());

    byte[] netscapeCertTypeExtValue = resultCert
            .getExtensionValue(MiscObjectIdentifiers.netscapeCertType.getId());
    assertNotNull(netscapeCertTypeExtValue);
    DERBitString netscapeCertTypeExt = (DERBitString) X509ExtensionUtil
            .fromExtensionValue(netscapeCertTypeExtValue);
    NetscapeCertType netscapeCertType = new NetscapeCertType(netscapeCertTypeExt);
    assertEquals(NetscapeCertType.sslClient, netscapeCertType.intValue() & NetscapeCertType.sslClient);
    assertEquals(NetscapeCertType.sslServer, netscapeCertType.intValue() & NetscapeCertType.sslServer);

    assertTrue(resultCert.getKeyUsage()[0]);
    assertTrue(resultCert.getKeyUsage()[2]);

    byte[] extendedKeyUsageExtValue = resultCert.getExtensionValue(X509Extension.extendedKeyUsage.getId());
    assertNotNull(extendedKeyUsageExtValue);
    ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage
            .getInstance(X509ExtensionUtil.fromExtensionValue(extendedKeyUsageExtValue));
    assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth));
    assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth));
}