Example usage for org.bouncycastle.asn1 ASN1Integer getValue

List of usage examples for org.bouncycastle.asn1 ASN1Integer getValue

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1Integer getValue.

Prototype

public BigInteger getValue() 

Source Link

Usage

From source file:eu.europa.esig.dss.xades.signature.DSSSignatureUtils.java

License:Open Source License

/**
 * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value.
 *
 * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value pairs; the XML Signature requires the
 * core BigInteger values./*from  w  w w .  j  av  a  2s.  c o m*/
 *
 * @param binaries
 *            the ASN1 signature value
 * @return the decode bytes
 * @throws IOException
 * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
 * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
 */
private static byte[] convertECDSAASN1toXMLDSIG(byte[] binaries) {
    ASN1InputStream is = null;
    try {
        is = new ASN1InputStream(binaries);

        ASN1Sequence seq = (ASN1Sequence) is.readObject();
        if (seq.size() != 2) {
            throw new IllegalArgumentException("ASN1 Sequence size should be 2 !");
        }
        ASN1Integer r = (ASN1Integer) seq.getObjectAt(0);
        ASN1Integer s = (ASN1Integer) seq.getObjectAt(1);

        byte[] rBytes = r.getValue().toByteArray();
        int rSize = rBytes.length;
        byte[] sBytes = s.getValue().toByteArray();
        int sSize = sBytes.length;

        int max = Math.max(rSize, sSize);

        ByteArrayOutputStream buffer = new ByteArrayOutputStream(max * 2);
        if (sSize > rSize) {
            buffer.write(0x00);
        }
        buffer.write(rBytes);
        if (rSize > sSize) {
            buffer.write(0x00);
        }
        buffer.write(sBytes);
        return buffer.toByteArray();
    } catch (Exception e) {
        throw new DSSException("Unable to convert to xmlDsig : " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:eu.europa.esig.dss.xades.signature.DSSSignatureUtils.java

License:Open Source License

/**
 * Converts an ASN.1 DSA value to a XML Signature DSA Value.
 *
 * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value pairs; the XML Signature requires the
 * core BigInteger values./*from  w w w  . j  a  v a2  s . c  o m*/
 *
 * @param binaries
 *            the ASN1 signature value
 * @return the decode bytes
 * @throws IOException
 * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
 * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
 */
private static byte[] convertDSAASN1toXMLDSIG(byte[] binaries) {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    ASN1InputStream is = null;
    try {
        is = new ASN1InputStream(binaries);

        ASN1Sequence seq = (ASN1Sequence) is.readObject();
        if (seq.size() != 2) {
            throw new IllegalArgumentException("ASN1 Sequence size should be 2 !");
        }

        ASN1Integer r = (ASN1Integer) seq.getObjectAt(0);
        ASN1Integer s = (ASN1Integer) seq.getObjectAt(1);

        buffer.write(BigIntegers.asUnsignedByteArray(r.getValue()));
        buffer.write(BigIntegers.asUnsignedByteArray(s.getValue()));
    } catch (Exception e) {
        throw new DSSException("Unable to convert to xmlDsig : " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(is);
    }
    return buffer.toByteArray();
}

From source file:eu.europa.esig.dss.xades.validation.XAdESSignature.java

License:Open Source License

@Override
public void checkSigningCertificate() {

    final CandidatesForSigningCertificate candidates = getCandidatesForSigningCertificate();
    /**//  w  w w  .jav  a 2s .co  m
     * The ../SignedProperties/SignedSignatureProperties/SigningCertificate element MAY contain references and
     * digests values of other certificates (that
     * MAY form a chain up to the point of trust).
     */
    boolean isEn319132 = false;
    NodeList list = DSSXMLUtils.getNodeList(signatureElement, xPathQueryHolder.XPATH_SIGNING_CERTIFICATE_CERT);
    int length = list.getLength();
    if (length == 0) {
        list = DSSXMLUtils.getNodeList(signatureElement, xPathQueryHolder.XPATH_SIGNING_CERTIFICATE_CERT_V2);
        length = list.getLength();
        isEn319132 = true;
    }
    if (length == 0) {
        final CertificateValidity theCertificateValidity = candidates.getTheCertificateValidity();
        final CertificateToken certificateToken = theCertificateValidity == null ? null
                : theCertificateValidity.getCertificateToken();
        // The check need to be done at the level of KeyInfo
        for (final Reference reference : references) {

            final String uri = reference.getURI();
            if (!uri.startsWith("#")) {
                continue;
            }

            final String id = uri.substring(1);
            final Element element = signatureElement.getOwnerDocument().getElementById(id);
            // final Element element =
            // DSSXMLUtils.getElement(signatureElement, "");
            if (!hasSignatureAsParent(element)) {

                continue;
            }
            if ((certificateToken != null) && id.equals(certificateToken.getXmlId())) {

                theCertificateValidity.setSigned(element.getNodeName());
                return;
            }
        }
    }
    // This Map contains the list of the references to the certificate which
    // were already checked and which correspond to a certificate.
    Map<Element, Boolean> alreadyProcessedElements = new HashMap<Element, Boolean>();

    final List<CertificateValidity> certificateValidityList = candidates.getCertificateValidityList();
    for (final CertificateValidity certificateValidity : certificateValidityList) {

        final CertificateToken certificateToken = certificateValidity.getCertificateToken();
        for (int ii = 0; ii < length; ii++) {

            certificateValidity.setAttributePresent(true);
            final Element element = (Element) list.item(ii);
            if (alreadyProcessedElements.containsKey(element)) {
                continue;
            }
            final Element certDigestElement = DSSXMLUtils.getElement(element,
                    xPathQueryHolder.XPATH__CERT_DIGEST);
            certificateValidity.setDigestPresent(certDigestElement != null);

            final Element digestMethodElement = DSSXMLUtils.getElement(certDigestElement,
                    xPathQueryHolder.XPATH__DIGEST_METHOD);
            if (digestMethodElement == null) {
                continue;
            }
            final String xmlAlgorithmName = digestMethodElement.getAttribute(XMLE_ALGORITHM);
            // The default algorithm is used in case of bad encoded
            // algorithm name
            final DigestAlgorithm digestAlgorithm = DigestAlgorithm.forXML(xmlAlgorithmName,
                    DigestAlgorithm.SHA1);

            final Element digestValueElement = DSSXMLUtils.getElement(element,
                    xPathQueryHolder.XPATH__CERT_DIGEST_DIGEST_VALUE);
            if (digestValueElement == null) {
                continue;
            }
            // That must be a binary comparison
            final byte[] storedBase64DigestValue = DSSUtils
                    .base64StringToBase64Binary(digestValueElement.getTextContent());

            /**
             * Step 1:<br>
             * Take the first child of the property and check that the content of ds:DigestValue matches the result
             * of digesting <i>the candidate for</i>
             * the signing certificate with the algorithm indicated in ds:DigestMethod. If they do not match, take
             * the next child and repeat this step until
             * a matching child element has been found or all children of the element have been checked. If they do
             * match, continue with step 2. If the last
             * element is reached without finding any match, the validation of this property shall be taken as
             * failed and INVALID/FORMAT_FAILURE is
             * returned.
             */
            final byte[] digest = DSSUtils.digest(digestAlgorithm, certificateToken.getEncoded());
            final byte[] recalculatedBase64DigestValue = Base64.encodeBase64(digest);
            certificateValidity.setDigestEqual(false);
            BigInteger serialNumber = new BigInteger("0");
            if (Arrays.equals(recalculatedBase64DigestValue, storedBase64DigestValue)) {
                X500Principal issuerName = null;
                if (isEn319132) {
                    final Element issuerNameEl = DSSXMLUtils.getElement(element,
                            xPathQueryHolder.XPATH__X509_ISSUER_V2);
                    if (issuerNameEl != null) {
                        final String textContent = issuerNameEl.getTextContent();

                        ASN1InputStream is = null;
                        GeneralName name = null;
                        ASN1Integer serial = null;
                        try {
                            is = new ASN1InputStream(Base64.decodeBase64(textContent));
                            ASN1Sequence seq = (ASN1Sequence) is.readObject();
                            ASN1Sequence obj = (ASN1Sequence) seq.getObjectAt(0);
                            name = GeneralName.getInstance(obj.getObjectAt(0));
                            serial = (ASN1Integer) seq.getObjectAt(1);
                        } catch (IOException e) {
                            LOG.error("Unable to decode textContent " + textContent + " : " + e.getMessage(),
                                    e);
                        } finally {
                            IOUtils.closeQuietly(is);
                        }

                        try {
                            issuerName = new X500Principal(name.getName().toASN1Primitive().getEncoded());
                        } catch (Exception e) {
                            LOG.error("Unable to decode X500Principal : " + e.getMessage(), e);
                        }

                        try {
                            serialNumber = serial.getValue();
                        } catch (Exception e) {
                            LOG.error("Unable to decode serialNumber : " + e.getMessage(), e);
                        }

                    }
                } else {
                    final Element issuerNameEl = DSSXMLUtils.getElement(element,
                            xPathQueryHolder.XPATH__X509_ISSUER_NAME);
                    // This can be allayed when the distinguished name is not
                    // correctly encoded
                    // final String textContent =
                    // DSSUtils.unescapeMultiByteUtf8Literals(issuerNameEl.getTextContent());
                    final String textContent = issuerNameEl.getTextContent();

                    issuerName = DSSUtils.getX500PrincipalOrNull(textContent);

                    final Element serialNumberEl = DSSXMLUtils.getElement(element,
                            xPathQueryHolder.XPATH__X509_SERIAL_NUMBER);
                    final String serialNumberText = serialNumberEl.getTextContent();
                    // serial number can contain leading and trailing whitespace.
                    serialNumber = new BigInteger(serialNumberText.trim());
                }
                final X500Principal candidateIssuerName = certificateToken.getIssuerX500Principal();

                final boolean issuerNameMatches = DSSUtils.x500PrincipalAreEquals(candidateIssuerName,
                        issuerName);
                if (!issuerNameMatches) {
                    final String c14nCandidateIssuerName = candidateIssuerName.getName(X500Principal.CANONICAL);
                    LOG.info("candidateIssuerName: " + c14nCandidateIssuerName);
                    final String c14nIssuerName = issuerName == null ? ""
                            : issuerName.getName(X500Principal.CANONICAL);
                    LOG.info("issuerName         : " + c14nIssuerName);
                }

                final BigInteger candidateSerialNumber = certificateToken.getSerialNumber();
                final boolean serialNumberMatches = candidateSerialNumber.equals(serialNumber);

                certificateValidity.setDigestEqual(true);
                certificateValidity.setSerialNumberEqual(serialNumberMatches);
                certificateValidity.setDistinguishedNameEqual(issuerNameMatches);
                // The certificate was identified
                alreadyProcessedElements.put(element, true);
                // If the signing certificate is not set yet then it must be
                // done now. Actually if the signature is tempered then the
                // method checkSignatureIntegrity cannot set the signing
                // certificate.
                if (candidates.getTheCertificateValidity() == null) {
                    candidates.setTheCertificateValidity(certificateValidity);
                }
                break;
            }
        }
    }
}

From source file:jcifs.pac.kerberos.KerberosApRequest.java

License:Open Source License

public KerberosApRequest(byte[] token, KerberosKey[] keys) throws PACDecodingException {
    if (token.length <= 0)
        throw new PACDecodingException("Empty kerberos ApReq");

    DLSequence sequence;/*from   w w w .j  a v  a 2  s  .  c  o  m*/
    try {
        try (ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token))) {
            sequence = ASN1Util.as(DLSequence.class, stream);
        }
    } catch (IOException e) {
        throw new PACDecodingException("Malformed Kerberos Ticket", e);
    }

    Enumeration<?> fields = sequence.getObjects();
    while (fields.hasMoreElements()) {
        ASN1TaggedObject tagged = ASN1Util.as(ASN1TaggedObject.class, fields.nextElement());
        switch (tagged.getTagNo()) {
        case 0:
            ASN1Integer pvno = ASN1Util.as(ASN1Integer.class, tagged);
            if (!pvno.getValue().equals(new BigInteger(KerberosConstants.KERBEROS_VERSION))) {
                throw new PACDecodingException("Invalid kerberos version");
            }
            break;
        case 1:
            ASN1Integer msgType = ASN1Util.as(ASN1Integer.class, tagged);
            if (!msgType.getValue().equals(new BigInteger(KerberosConstants.KERBEROS_AP_REQ)))
                throw new PACDecodingException("Invalid kerberos request");
            break;
        case 2:
            DERBitString bitString = ASN1Util.as(DERBitString.class, tagged);
            this.apOptions = bitString.getBytes()[0];
            break;
        case 3:
            DERApplicationSpecific derTicket = ASN1Util.as(DERApplicationSpecific.class, tagged);
            if (!derTicket.isConstructed())
                throw new PACDecodingException("Malformed Kerberos Ticket");
            this.ticket = new KerberosTicket(derTicket.getContents(), this.apOptions, keys);
            break;
        case 4:
            // Let's ignore this for now
            break;
        default:
            throw new PACDecodingException("Invalid field in kerberos ticket");
        }
    }
}

From source file:jcifs.pac.kerberos.KerberosEncData.java

License:Open Source License

public KerberosEncData(byte[] token, Key key) throws PACDecodingException {
    ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token));
    DERApplicationSpecific derToken;/*from  ww w  .  j  ava  2  s. co m*/
    try {
        derToken = ASN1Util.as(DERApplicationSpecific.class, stream);
        if (!derToken.isConstructed())
            throw new PACDecodingException("Malformed kerberos ticket");
        stream.close();
    } catch (IOException e) {
        throw new PACDecodingException("Malformed kerberos ticket", e);
    }

    stream = new ASN1InputStream(new ByteArrayInputStream(derToken.getContents()));
    DLSequence sequence;
    try {
        sequence = ASN1Util.as(DLSequence.class, stream);
        stream.close();
    } catch (IOException e) {
        throw new PACDecodingException("Malformed kerberos ticket", e);
    }

    Enumeration<?> fields = sequence.getObjects();
    while (fields.hasMoreElements()) {
        ASN1TaggedObject tagged = ASN1Util.as(ASN1TaggedObject.class, fields);

        switch (tagged.getTagNo()) {
        case 0: // Ticket Flags
            break;
        case 1: // Key
            break;
        case 2: // Realm
            DERGeneralString derRealm = ASN1Util.as(DERGeneralString.class, tagged);
            this.userRealm = derRealm.getString();
            break;
        case 3: // Principal
            DLSequence principalSequence = ASN1Util.as(DLSequence.class, tagged);
            DLSequence nameSequence = ASN1Util.as(DLSequence.class,
                    ASN1Util.as(DERTaggedObject.class, principalSequence, 1));

            StringBuilder nameBuilder = new StringBuilder();
            Enumeration<?> parts = nameSequence.getObjects();
            while (parts.hasMoreElements()) {
                Object part = parts.nextElement();
                DERGeneralString stringPart = ASN1Util.as(DERGeneralString.class, part);
                nameBuilder.append(stringPart.getString());
                if (parts.hasMoreElements())
                    nameBuilder.append('/');
            }
            this.userPrincipalName = nameBuilder.toString();
            break;
        case 4: // Transited Encoding
            break;
        case 5: // Kerberos Time
            // DERGeneralizedTime derTime = KerberosUtil.readAs(tagged,
            // DERGeneralizedTime.class);
            break;
        case 6: // Kerberos Time
            // DERGeneralizedTime derTime = KerberosUtil.readAs(tagged,
            // DERGeneralizedTime.class);
            break;
        case 7: // Kerberos Time
            // DERGeneralizedTime derTime = KerberosUtil.readAs(tagged,
            // DERGeneralizedTime.class);
            break;
        case 8: // Kerberos Time
            // DERGeneralizedTime derTime = KerberosUtil.readAs(tagged,
            // DERGeneralizedTime.class);
            break;
        case 9: // Host Addresses
            DLSequence adressesSequence = ASN1Util.as(DLSequence.class, tagged);
            Enumeration<?> adresses = adressesSequence.getObjects();
            while (adresses.hasMoreElements()) {
                DLSequence addressSequence = ASN1Util.as(DLSequence.class, adresses);
                ASN1Integer addressType = ASN1Util.as(ASN1Integer.class, addressSequence, 0);
                DEROctetString addressOctets = ASN1Util.as(DEROctetString.class, addressSequence, 1);

                this.userAddresses = new ArrayList<>();
                if (addressType.getValue().intValue() == KerberosConstants.AF_INTERNET) {
                    InetAddress userAddress = null;
                    try {
                        userAddress = InetAddress.getByAddress(addressOctets.getOctets());
                    } catch (UnknownHostException e) {
                    }
                    this.userAddresses.add(userAddress);
                }
            }
            break;
        case 10: // Authorization Data
            DLSequence authSequence = ASN1Util.as(DLSequence.class, tagged);

            this.userAuthorizations = new ArrayList<>();
            Enumeration<?> authElements = authSequence.getObjects();
            while (authElements.hasMoreElements()) {
                DLSequence authElement = ASN1Util.as(DLSequence.class, authElements);
                ASN1Integer authType = ASN1Util.as(ASN1Integer.class,
                        ASN1Util.as(DERTaggedObject.class, authElement, 0));
                DEROctetString authData = ASN1Util.as(DEROctetString.class,
                        ASN1Util.as(DERTaggedObject.class, authElement, 1));

                this.userAuthorizations.addAll(
                        KerberosAuthData.parse(authType.getValue().intValue(), authData.getOctets(), key));
            }
            break;
        default:
            throw new PACDecodingException("Unknown field " + tagged.getTagNo());
        }
    }
}

From source file:jcifs.pac.kerberos.KerberosRelevantAuthData.java

License:Open Source License

public KerberosRelevantAuthData(byte[] token, Key key) throws PACDecodingException {
    DLSequence authSequence;/*from   www.  j  a va2  s.c om*/
    try {
        try (ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token))) {
            authSequence = ASN1Util.as(DLSequence.class, stream);
        }
    } catch (IOException e) {
        throw new PACDecodingException("Malformed kerberos ticket", e);
    }

    this.authorizations = new ArrayList<>();
    Enumeration<?> authElements = authSequence.getObjects();
    while (authElements.hasMoreElements()) {
        DLSequence authElement = ASN1Util.as(DLSequence.class, authElements);
        ASN1Integer authType = ASN1Util.as(ASN1Integer.class,
                ASN1Util.as(DERTaggedObject.class, authElement, 0));
        DEROctetString authData = ASN1Util.as(DEROctetString.class,
                ASN1Util.as(DERTaggedObject.class, authElement, 1));

        this.authorizations
                .addAll(KerberosAuthData.parse(authType.getValue().intValue(), authData.getOctets(), key));
    }
}

From source file:jcifs.pac.kerberos.KerberosTicket.java

License:Open Source License

public KerberosTicket(byte[] token, byte apOptions, KerberosKey[] keys) throws PACDecodingException {
    if (token.length <= 0)
        throw new PACDecodingException("Empty kerberos ticket");

    DLSequence sequence;/*from w  ww . ja v a  2 s  .c  o m*/
    try {
        try (ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token))) {
            sequence = ASN1Util.as(DLSequence.class, stream);
        }
    } catch (IOException e) {
        throw new PACDecodingException("Malformed kerberos ticket", e);
    }

    Enumeration<?> fields = sequence.getObjects();
    while (fields.hasMoreElements()) {
        ASN1TaggedObject tagged = ASN1Util.as(ASN1TaggedObject.class, fields);
        switch (tagged.getTagNo()) {
        case 0:// Kerberos version
            ASN1Integer tktvno = ASN1Util.as(ASN1Integer.class, tagged);
            if (!tktvno.getValue().equals(new BigInteger(KerberosConstants.KERBEROS_VERSION))) {
                throw new PACDecodingException("Invalid kerberos version " + tktvno);
            }
            break;
        case 1:// Realm
            DERGeneralString derRealm = ASN1Util.as(DERGeneralString.class, tagged);
            this.serverRealm = derRealm.getString();
            break;
        case 2:// Principal
            DLSequence principalSequence = ASN1Util.as(DLSequence.class, tagged);
            DLSequence nameSequence = ASN1Util.as(DLSequence.class,
                    ASN1Util.as(DERTaggedObject.class, principalSequence, 1));

            StringBuilder nameBuilder = new StringBuilder();
            Enumeration<?> parts = nameSequence.getObjects();
            while (parts.hasMoreElements()) {
                Object part = parts.nextElement();
                DERGeneralString stringPart = ASN1Util.as(DERGeneralString.class, part);
                nameBuilder.append(stringPart.getString());
                if (parts.hasMoreElements())
                    nameBuilder.append('/');
            }
            this.serverPrincipalName = nameBuilder.toString();
            break;
        case 3:// Encrypted part
            DLSequence encSequence = ASN1Util.as(DLSequence.class, tagged);
            ASN1Integer encType = ASN1Util.as(ASN1Integer.class,
                    ASN1Util.as(DERTaggedObject.class, encSequence, 0));
            DEROctetString encOctets = ASN1Util.as(DEROctetString.class,
                    ASN1Util.as(DERTaggedObject.class, encSequence, 2));
            byte[] crypt = encOctets.getOctets();

            if (keys == null) {
                try {
                    keys = new KerberosCredentials().getKeys();
                } catch (LoginException e) {
                    throw new PACDecodingException("Login failure", e);
                }
            }

            KerberosKey serverKey = null;
            for (KerberosKey key : keys) {
                if (key.getKeyType() == encType.getValue().intValue())
                    serverKey = key;
            }

            if (serverKey == null) {
                throw new PACDecodingException("Kerberos key not found for eType " + encType.getValue());
            }

            try {
                byte[] decrypted = KerberosEncData.decrypt(crypt, serverKey, serverKey.getKeyType());
                this.encData = new KerberosEncData(decrypted, serverKey);
            } catch (GeneralSecurityException e) {
                throw new PACDecodingException("Decryption failed " + serverKey.getKeyType(), e);
            }
            break;
        default:
            throw new PACDecodingException("Unrecognized field " + tagged.getTagNo());
        }
    }

}

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//  w w w  . j a  v  a 2 s . 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.Pkcs8Util.java

License:Open Source License

/**
 * Detect if a PKCS #8 private key is encrypted or not.
 *
 * @param is//  ww w  .  j  av  a  2s .c om
 *            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.x509.PolicyInformationUtil.java

License:Open Source License

/**
 * Get string representation of user notice.
 *
 * @param userNotice//from  ww  w  .  ja  v  a 2 s  . co m
 *            User notice
 * @return String representation of user notice
 */
public static String toString(UserNotice userNotice) {
    StringBuffer sbUserNotice = new StringBuffer();

    NoticeReference noticeReference = userNotice.getNoticeRef();

    if (noticeReference != null) {
        DisplayText organization = noticeReference.getOrganization();

        if (organization != null) {
            sbUserNotice.append(MessageFormat.format(res.getString("PolicyInformationUtil.Organization"),
                    organization.getString()));

            if ((noticeReference.getNoticeNumbers() != null) || (userNotice.getExplicitText() != null)) {
                sbUserNotice.append(", ");
            }
        }

        ASN1Integer[] noticeNumbers = noticeReference.getNoticeNumbers();

        StringBuffer sbNoticeNumbers = new StringBuffer();

        if (noticeNumbers != null) {
            for (int i = 0; i < noticeNumbers.length; i++) {
                ASN1Integer noticeNumber = noticeNumbers[i];

                sbNoticeNumbers.append(noticeNumber.getValue().intValue());

                if ((i + 1) < noticeNumbers.length) {
                    sbNoticeNumbers.append(" ");
                }
            }

            sbUserNotice.append(MessageFormat.format(res.getString("PolicyInformationUtil.NoticeNumbers"),
                    sbNoticeNumbers.toString()));

            if (userNotice.getExplicitText() != null) {
                sbUserNotice.append(", ");
            }
        }
    }

    DisplayText explicitText = userNotice.getExplicitText();

    if (explicitText != null) {
        sbUserNotice.append(MessageFormat.format(res.getString("PolicyInformationUtil.ExplicitText"),
                explicitText.getString()));
    }

    return sbUserNotice.toString();
}