Example usage for org.bouncycastle.asn1 ASN1Sequence getObjectAt

List of usage examples for org.bouncycastle.asn1 ASN1Sequence getObjectAt

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1Sequence getObjectAt.

Prototype

public ASN1Encodable getObjectAt(int index) 

Source Link

Document

Return the object at the sequence position indicated by index.

Usage

From source file:net.ripe.rpki.commons.crypto.x509cert.X509ResourceCertificateParser.java

License:BSD License

private void validateCertificatePolicy() {
    if (!result.rejectIfNull(certificate.getCriticalExtensionOIDs(), CRITICAL_EXT_PRESENT)) {
        return;//from   w w w  .  j av a 2 s .  co m
    }

    result.rejectIfFalse(
            certificate.getCriticalExtensionOIDs().contains(X509Extension.certificatePolicies.getId()),
            POLICY_EXT_CRITICAL);

    try {
        byte[] extensionValue = certificate.getExtensionValue(X509Extension.certificatePolicies.getId());
        if (!result.rejectIfNull(extensionValue, POLICY_EXT_VALUE)) {
            return;
        }
        ASN1Sequence policies = ASN1Sequence.getInstance(X509ExtensionUtil.fromExtensionValue(extensionValue));
        if (!result.rejectIfFalse(policies.size() == 1, SINGLE_CERT_POLICY)) {
            return;
        }
        PolicyInformation policy = PolicyInformation.getInstance(policies.getObjectAt(0));

        if (!result.rejectIfNull(policy.getPolicyIdentifier(), POLICY_ID_PRESENT)) {
            return;
        }
        result.rejectIfFalse(POLICY_OID.equals(policy.getPolicyIdentifier()), POLICY_ID_VERSION);
    } catch (IOException e) {
        result.rejectIfFalse(false, POLICY_VALIDATION);
    }
}

From source file:net.sf.keystore_explorer.crypto.csr.spkac.Spkac.java

License:Open Source License

private void decodeSpkac(byte[] der) throws SpkacException {
    try {/*from  ww  w  .  ja  v a2s.c o m*/
        ASN1Sequence signedPublicKeyAndChallenge = ASN1Sequence.getInstance(der);

        ASN1Sequence publicKeyAndChallenge = (ASN1Sequence) signedPublicKeyAndChallenge.getObjectAt(0);
        ASN1Sequence signatureAlgorithm = (ASN1Sequence) signedPublicKeyAndChallenge.getObjectAt(1);
        DERBitString signature = (DERBitString) signedPublicKeyAndChallenge.getObjectAt(2);

        ASN1ObjectIdentifier signatureAlgorithmOid = (ASN1ObjectIdentifier) signatureAlgorithm.getObjectAt(0);

        ASN1Sequence spki = (ASN1Sequence) publicKeyAndChallenge.getObjectAt(0);
        DERIA5String challenge = (DERIA5String) publicKeyAndChallenge.getObjectAt(1);

        ASN1Sequence publicKeyAlgorithm = (ASN1Sequence) spki.getObjectAt(0);
        DERBitString publicKey = (DERBitString) spki.getObjectAt(1);

        ASN1ObjectIdentifier publicKeyAlgorithmOid = (ASN1ObjectIdentifier) publicKeyAlgorithm.getObjectAt(0);
        ASN1Primitive algorithmParameters = publicKeyAlgorithm.getObjectAt(1).toASN1Primitive();

        this.challenge = challenge.getString();
        this.publicKey = decodePublicKeyFromBitString(publicKeyAlgorithmOid, algorithmParameters, publicKey);
        this.signatureAlgorithm = getSignatureAlgorithm(signatureAlgorithmOid);
        this.signature = signature.getBytes();
    } catch (Exception ex) {
        throw new SpkacException(res.getString("NoDecodeSpkac.exception.message"), ex);
    }
}

From source file:net.sf.keystore_explorer.crypto.csr.spkac.Spkac.java

License:Open Source License

private PublicKey decodePublicKeyFromBitString(ASN1ObjectIdentifier publicKeyAlgorithmOid,
        ASN1Primitive algorithmParameters, DERBitString publicKey) throws SpkacException {
    if (publicKeyAlgorithmOid.getId().equals(RSA.oid())) {
        return decodeRsaPublicKeyFromBitString(publicKey); // Algorithm parameters are ASN1Null and unnecessary
    } else if (publicKeyAlgorithmOid.getId().equals(DSA.oid())) {
        ASN1Sequence dssParams = (ASN1Sequence) algorithmParameters;

        BigInteger p = ((ASN1Integer) dssParams.getObjectAt(0)).getValue();
        BigInteger q = ((ASN1Integer) dssParams.getObjectAt(1)).getValue();
        BigInteger g = ((ASN1Integer) dssParams.getObjectAt(2)).getValue();

        return decodeDsaPublicKeyFromBitString(publicKey, p, q, g);
    } else {//w w w .j a  v a2s . c  om
        throw new SpkacException(MessageFormat.format(
                res.getString("NoSupportPublicKeyAlgorithm.exception.message"), publicKeyAlgorithmOid.getId()));

    }
}

From source file:net.sf.keystore_explorer.crypto.csr.spkac.Spkac.java

License:Open Source License

private RSAPublicKey decodeRsaPublicKeyFromBitString(DERBitString der) throws SpkacException {
    try {//from  w  ww  .jav  a  2 s.  co  m
        ASN1Sequence rsaPublicKey = ASN1Sequence.getInstance(der.getBytes());

        BigInteger modulus = ((ASN1Integer) rsaPublicKey.getObjectAt(0)).getValue();
        BigInteger publicExponent = ((ASN1Integer) rsaPublicKey.getObjectAt(1)).getValue();

        KeyFactory keyFact = KeyFactory.getInstance("RSA");

        return (RSAPublicKey) keyFact.generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
    } catch (GeneralSecurityException ex) {
        throw new SpkacException(res.getString("NoGenerateRsaPublicKeyFromSpkac.exception.message"), ex);
    } catch (Exception ex) {
        throw new SpkacException(res.getString("NoGenerateRsaPublicKeyFromSpkac.exception.message"), ex);
    }
}

From source file:net.sf.keystore_explorer.crypto.filetype.CryptoFileUtil.java

License:Open Source License

/**
 * Detect the KeyStore type contained in the supplied file.
 *
 * @param is//from  w w  w  .  ja v a2s.  c  o  m
 *            Input stream to detect type for
 * @return KeyStore type or null if none matched
 * @throws IOException
 *             If an I/O problem occurred
 */
public static KeyStoreType detectKeyStoreType(InputStream is) throws IOException {
    byte[] contents = ReadUtil.readFully(is);

    DataInputStream dis = null;

    try {
        dis = new DataInputStream(new ByteArrayInputStream(contents));

        // If less than 4 bytes are available it isn't a KeyStore
        if (dis.available() < 4) {
            return null;
        }

        // Read first integer (4 bytes)
        int i1 = dis.readInt();

        // Test for JKS - starts with appropriate magic number
        if (i1 == JKS_MAGIC_NUMBER) {
            return JKS;
        }

        if (i1 == HTKS_MAGIC_NUMBER) {
            return HTKS;
        }

        // Test for JCEKS - starts with appropriate magic number
        if (i1 == JCEKS_MAGIC_NUMBER) {
            return JCEKS;
        }

        // Test for BKS and UBER

        // Both start with a version number of 0, 1 or 2
        if ((i1 == 0) || (i1 == 1) || (i1 == 2)) {
            /*
             * For BKS and UBER the last 20 bytes of the file are the SHA-1
             * Hash while the byte before that is a ASN1Null (0) indicating
             * the end of the store. UBER, however, encrypts the store
             * content making it highly unlikely that the ASN1Null end byte
             * will be preserved. Therefore if the 21st byte from the end of
             * the file is a ASN1Null then the KeyStore is BKS
             */

            if (contents.length < 26) {
                // Insufficient bytes to be BKS or UBER
                return null;
            }

            // Skip to 21st from last byte (file length minus 21 and the 4 bytes already read)
            dis.skip(contents.length - 25);

            // Read what may be the null byte
            if (dis.readByte() == 0) {
                // Found null byte - BKS/BKS-V1
                if (i1 == 1) {
                    return BKS_V1;
                } else {
                    return BKS;
                }
            } else {
                // No null byte - UBER
                return UBER;
            }
        }
    } finally {
        IOUtils.closeQuietly(dis);
    }

    // @formatter:off
    /*
     * Test for PKCS #12. ASN.1 should look like this:
     *
     * PFX ::= ASN1Sequence { version ASN1Integer {v3(3)}(v3,...), authSafe
     * ContentInfo, macData MacData OPTIONAL
     */
    // @formatter:on

    ASN1Primitive pfx = null;
    try {
        pfx = ASN1Primitive.fromByteArray(contents);
    } catch (IOException e) {
        // if it cannot be parsed as ASN1, it is certainly not a pfx key store
        return null;
    }

    // Is a sequence...
    if ((pfx != null) && (pfx instanceof ASN1Sequence)) {
        // Has two or three components...
        ASN1Sequence sequence = (ASN1Sequence) pfx;

        if ((sequence.size() == 2) || (sequence.size() == 3)) {
            // ...the first of which is a version of 3
            ASN1Encodable firstComponent = sequence.getObjectAt(0);

            if (firstComponent instanceof ASN1Integer) {
                ASN1Integer version = (ASN1Integer) firstComponent;

                if (version.getValue().intValue() == 3) {
                    return PKCS12;
                }
            }
        }
    }

    // KeyStore type not recognised
    return null;
}

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.//ww w  . jav a 2  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.OpenSslPvkUtil.java

License:Open Source License

/**
 * Detect if a OpenSSL private key is encrypted or not.
 *
 * @param is/*from www  .  ja  v a  2s  .  c  om*/
 *            Input stream containing OpenSSL private key
 * @return Encryption type or null if not a valid OpenSSL private key
 * @throws IOException
 *             If an I/O problem occurred
 */
public static EncryptionType getEncryptionType(InputStream is) throws IOException {
    byte[] openSsl = ReadUtil.readFully(is);

    // In pem format?
    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(openSsl));

    if (pemInfo != null) {
        String pemType = pemInfo.getType();

        // PEM type of OpenSSL?
        if ((pemType.equals(OPENSSL_RSA_PVK_PEM_TYPE)) || (pemType.equals(OPENSSL_DSA_PVK_PEM_TYPE))) {
            // Encrypted? It is if pem contains appropriate header
            // attributes/values
            PemAttributes pemAttributes = pemInfo.getAttributes();

            if ((pemAttributes != null) && (pemAttributes.get(PROC_TYPE_ATTR_NAME) != null)
                    && (pemAttributes.get(PROC_TYPE_ATTR_NAME).getValue().equals(PROC_TYPE_ATTR_VALUE))
                    && (pemAttributes.get(DEK_INFO_ATTR_NAME) != null)) {
                return ENCRYPTED;
            } else {
                return UNENCRYPTED;
            }
        }
    }

    // In ASN.1 format?
    try {
        // If OpenSSL will be a sequence of 9 (RSA) or 6 (DSA) integers
        ASN1Primitive key = ASN1Primitive.fromByteArray(openSsl);

        if (key instanceof ASN1Sequence) {
            ASN1Sequence sequence = (ASN1Sequence) key;

            for (int i = 0; i < sequence.size(); i++) {
                if (!(sequence.getObjectAt(i) instanceof ASN1Integer)) {
                    return null; // Not OpenSSL
                }
            }

            if ((sequence.size() == 9) || (sequence.size() == 6)) {
                return UNENCRYPTED; // ASN.1 OpenSSL is always unencrypted
            }
        }
    } catch (IOException ex) {
        return null; // Not an OpenSSL file
    }

    return null; // Not an OpenSSL file
}

From source file:net.sf.keystore_explorer.crypto.privatekey.Pkcs8Util.java

License:Open Source License

/**
 * Detect if a PKCS #8 private key is encrypted or not.
 *
 * @param is//from ww w  . ja  va 2s  .  c  o m
 *            Input stream containing PKCS #8 private key
 * @return Encryption type or null if not a valid PKCS #8 private key
 * @throws IOException
 *             If an I/O problem occurred
 */
public static EncryptionType getEncryptionType(InputStream is) throws IOException {
    byte[] pkcs8 = ReadUtil.readFully(is);

    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(pkcs8));

    // PEM encoded?
    if (pemInfo != null) {
        String pemType = pemInfo.getType();

        // Encrypted in pem format?
        if (pemType.equals(Pkcs8Util.PKCS8_ENC_PVK_PEM_TYPE)) {
            return ENCRYPTED;
        }
        // Unencrypted in pem format?
        else if (pemType.equals(Pkcs8Util.PKCS8_UNENC_PVK_PEM_TYPE)) {
            return UNENCRYPTED;
        }
    }

    // In ASN.1 format?
    try {
        // Read in an ASN.1 and check structure against the following
        ASN1Primitive key = ASN1Primitive.fromByteArray(pkcs8);

        if (key instanceof ASN1Sequence) {
            ASN1Sequence sequence = (ASN1Sequence) key;

            // May be unencrypted
            if ((sequence.size() == 3) || (sequence.size() == 4)) {
                // @formatter:off

                /*
                 * Unencrypted PKCS #8 Private Key:
                 *
                 * PrivateKeyInfo ::= ASN1Sequence { version Version,
                 * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
                 * privateKey PrivateKey, attributes [0] IMPLICIT Attributes
                 * OPTIONAL }
                 *
                 * Version ::= ASN1Integer PrivateKeyAlgorithmIdentifier ::=
                 * AlgorithmIdentifier PrivateKey ::= OCTET STRING
                 * Attributes ::= SET OF Attribute
                 */

                // @formatter:on

                Object obj1 = sequence.getObjectAt(0);
                Object obj2 = sequence.getObjectAt(1);
                Object obj3 = sequence.getObjectAt(2);

                if (!(obj1 instanceof ASN1Integer)) {
                    return null;
                }

                ASN1Integer version = (ASN1Integer) obj1;

                if (!version.getValue().equals(BigInteger.ZERO)) {
                    return null;
                }

                if (!(obj2 instanceof ASN1Sequence)) {
                    return null;
                }

                if (!sequenceIsAlgorithmIdentifier((ASN1Sequence) obj2)) {
                    return null;
                }

                if (!(obj3 instanceof ASN1OctetString)) {
                    return null;
                }

                return UNENCRYPTED;
            }
            // May be encrypted
            else if (sequence.size() == 2) {
                // @formatter:off

                /*
                 * Encrypted PKCS #8 Private Key:
                 *
                 * EncryptedPrivateKeyInfo ::= ASN1Sequence {
                 * encryptionAlgorithm EncryptionAlgorithmIdentifier,
                 * encryptedData EncryptedData }
                 *
                 * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
                 * EncryptedData ::= OCTET STRING
                 */

                // @formatter:on

                Object obj1 = sequence.getObjectAt(0);
                Object obj2 = sequence.getObjectAt(1);

                if (!(obj1 instanceof ASN1Sequence)) {
                    return null;
                }

                if (!sequenceIsAlgorithmIdentifier((ASN1Sequence) obj1)) {
                    return null;
                }

                if (!(obj2 instanceof ASN1OctetString)) {
                    return null;
                }

                return ENCRYPTED;
            }
        }
    } catch (Exception ex) {
        // Structure not as expected for PKCS #8
        return null;
    }

    return null;
}

From source file:net.sf.keystore_explorer.crypto.privatekey.Pkcs8Util.java

License:Open Source License

private static boolean sequenceIsAlgorithmIdentifier(ASN1Sequence sequence) {
    // @formatter:off

    /*//ww  w  . j  ava  2 s  . co  m
     * AlgorithmIdentifier ::= ASN1Sequence { algorithm OBJECT IDENTIFIER,
     * parameters ANY DEFINED BY algorithm OPTIONAL }
     */

    // @formatter:on

    if ((sequence.size() != 1) && (sequence.size() != 2)) {
        return false;
    }

    Object obj1 = sequence.getObjectAt(0);

    return obj1 instanceof ASN1ObjectIdentifier;

}

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

    /*//w  ww.  ja v  a2 s  .co  m
     * 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);
    }
}