Search in sources :

Example 41 with ASN1Primitive

use of com.github.zhenwei.core.asn1.ASN1Primitive in project keystore-explorer by kaikramer.

the class Pkcs8Util method getEncryptionType.

/**
 * Detect if a PKCS #8 private key is encrypted or not.
 *
 * @param is
 *            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;
        } else // Unencrypted in pem format?
        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;
            } else // May be encrypted
            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;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ByteArrayInputStream(java.io.ByteArrayInputStream) PemInfo(org.kse.utilities.pem.PemInfo) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CryptoException(org.kse.crypto.CryptoException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 42 with ASN1Primitive

use of com.github.zhenwei.core.asn1.ASN1Primitive in project keystore-explorer by kaikramer.

the class CryptoFileUtil method detectKeyStoreType.

/**
 * Detect the KeyStore type contained in the supplied file.
 *
 * @param is
 *            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);
    try (DataInputStream 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;
        }
        // Test for JCEKS - starts with appropriate magic number
        if (i1 == JCEKS_MAGIC_NUMBER) {
            return JCEKS;
        }
        // Both start with a version number of 0, 1 or 2
        if ((i1 == 0) || (i1 == 1) || (i1 == 2)) {
            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;
            }
        }
    }
    // @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;
}
Also used : ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) DataInputStream(java.io.DataInputStream) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive)

Example 43 with ASN1Primitive

use of com.github.zhenwei.core.asn1.ASN1Primitive in project xipki by xipki.

the class ExtensionsChecker method checkDirectoryString.

private void checkDirectoryString(ASN1ObjectIdentifier extType, QaDirectoryString conf, StringBuilder failureMsg, byte[] extensionValue, Extensions requestedExtensions, ExtensionControl extControl) {
    if (conf == null) {
        byte[] expected = getExpectedExtValue(extType, requestedExtensions, extControl);
        if (!Arrays.equals(expected, extensionValue)) {
            addViolation(failureMsg, "extension values", hex(extensionValue), (expected == null) ? "not present" : hex(expected));
        }
        return;
    }
    ASN1Primitive asn1;
    try {
        asn1 = ASN1Primitive.fromByteArray(extensionValue);
    } catch (IOException ex) {
        failureMsg.append("invalid syntax of extension value; ");
        return;
    }
    boolean correctStringType;
    switch(conf.getType()) {
        case bmpString:
            correctStringType = (asn1 instanceof DERBMPString);
            break;
        case printableString:
            correctStringType = (asn1 instanceof DERPrintableString);
            break;
        case teletexString:
            correctStringType = (asn1 instanceof DERT61String);
            break;
        case utf8String:
            correctStringType = (asn1 instanceof DERUTF8String);
            break;
        default:
            throw new RuntimeException("should not reach here, unknown DirectoryStringType " + conf.getType());
    }
    if (!correctStringType) {
        failureMsg.append("extension value is not of type DirectoryString.").append(conf.getText()).append("; ");
        return;
    }
    String extTextValue = ((ASN1String) asn1).getString();
    if (!conf.getText().equals(extTextValue)) {
        addViolation(failureMsg, "content", extTextValue, conf.getText());
    }
}
Also used : DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERBMPString(org.bouncycastle.asn1.DERBMPString) DERT61String(org.bouncycastle.asn1.DERT61String) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) IOException(java.io.IOException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) ASN1String(org.bouncycastle.asn1.ASN1String) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) QaDirectoryString(org.xipki.ca.qa.internal.QaDirectoryString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERT61String(org.bouncycastle.asn1.DERT61String) ASN1String(org.bouncycastle.asn1.ASN1String) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive)

Example 44 with ASN1Primitive

use of com.github.zhenwei.core.asn1.ASN1Primitive in project Pix-Art-Messenger by kriztan.

the class XmppDomainVerifier method parseOtherName.

private static Pair<String, String> parseOtherName(byte[] otherName) {
    try {
        ASN1Primitive asn1Primitive = ASN1Primitive.fromByteArray(otherName);
        if (asn1Primitive instanceof DERTaggedObject) {
            ASN1Primitive inner = ((DERTaggedObject) asn1Primitive).getObject();
            if (inner instanceof DLSequence) {
                DLSequence sequence = (DLSequence) inner;
                if (sequence.size() >= 2 && sequence.getObjectAt(1) instanceof DERTaggedObject) {
                    String oid = sequence.getObjectAt(0).toString();
                    ASN1Primitive value = ((DERTaggedObject) sequence.getObjectAt(1)).getObject();
                    if (value instanceof DERUTF8String) {
                        return new Pair<>(oid, ((DERUTF8String) value).getString());
                    } else if (value instanceof DERIA5String) {
                        return new Pair<>(oid, ((DERIA5String) value).getString());
                    }
                }
            }
        }
        return null;
    } catch (IOException e) {
        return null;
    }
}
Also used : DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERIA5String(org.bouncycastle.asn1.DERIA5String) DLSequence(org.bouncycastle.asn1.DLSequence) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) IOException(java.io.IOException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) Pair(android.util.Pair)

Example 45 with ASN1Primitive

use of com.github.zhenwei.core.asn1.ASN1Primitive in project certmgr by hdecarne.

the class PKCS10CertificateRequest method fromPKCS10.

/**
 * Construct {@code PKCS10CertificateRequest} from a PKCS#10 object.
 *
 * @param pkcs10 The PCKS#10 object.
 * @return The constructed {@code PKCS10CertificateRequest}.
 * @throws IOException if an I/O error occurs while accessing the PKCS#10 object.
 */
public static PKCS10CertificateRequest fromPKCS10(PKCS10CertificationRequest pkcs10) throws IOException {
    JcaPKCS10CertificationRequest csr;
    X500Principal subject;
    PublicKey publicKey;
    Map<String, byte[]> criticalExtensions = new HashMap<>();
    Map<String, byte[]> nonCriticalExtensions = new HashMap<>();
    try {
        if (pkcs10 instanceof JcaPKCS10CertificationRequest) {
            csr = (JcaPKCS10CertificationRequest) pkcs10;
        } else {
            csr = new JcaPKCS10CertificationRequest(pkcs10);
        }
        subject = new X500Principal(csr.getSubject().getEncoded());
        publicKey = csr.getPublicKey();
        Attribute[] extensionAttributes = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (extensionAttributes != null) {
            for (Attribute extensionAttribute : extensionAttributes) {
                ASN1Encodable[] values = extensionAttribute.getAttributeValues();
                if (values != null) {
                    for (ASN1Encodable value : values) {
                        ASN1Primitive[] extensionPrimitives = decodeSequence(value.toASN1Primitive(), 0, Integer.MAX_VALUE);
                        for (ASN1Primitive extensionPrimitive : extensionPrimitives) {
                            ASN1Primitive[] sequence = decodeSequence(extensionPrimitive, 2, 3);
                            String extensionOID = decodePrimitive(sequence[0], ASN1ObjectIdentifier.class).getId();
                            boolean criticalFlag = true;
                            byte[] extensionData;
                            if (sequence.length == 3) {
                                criticalFlag = decodePrimitive(sequence[1], ASN1Boolean.class).isTrue();
                                extensionData = sequence[2].getEncoded();
                            } else {
                                extensionData = sequence[1].getEncoded();
                            }
                            if (criticalFlag) {
                                criticalExtensions.put(extensionOID, extensionData);
                            } else {
                                nonCriticalExtensions.put(extensionOID, extensionData);
                            }
                        }
                    }
                }
            }
        }
    } catch (GeneralSecurityException e) {
        throw new CertProviderException(e);
    }
    return new PKCS10CertificateRequest(csr, subject, publicKey, criticalExtensions, nonCriticalExtensions);
}
Also used : JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) HashMap(java.util.HashMap) Attribute(org.bouncycastle.asn1.pkcs.Attribute) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) CertProviderException(de.carne.certmgr.certs.CertProviderException) X500Principal(javax.security.auth.x500.X500Principal) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)253 DERSequence (com.github.zhenwei.core.asn1.DERSequence)231 ASN1Primitive (org.bouncycastle.asn1.ASN1Primitive)177 IOException (java.io.IOException)107 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)62 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)57 DERTaggedObject (com.github.zhenwei.core.asn1.DERTaggedObject)55 ASN1Integer (com.github.zhenwei.core.asn1.ASN1Integer)42 DEROctetString (com.github.zhenwei.core.asn1.DEROctetString)38 ByteArrayInputStream (java.io.ByteArrayInputStream)38 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)32 ASN1Primitive (com.github.zhenwei.core.asn1.ASN1Primitive)31 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)31 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)30 DEROctetString (org.bouncycastle.asn1.DEROctetString)28 BigInteger (java.math.BigInteger)24 GeneralSecurityException (java.security.GeneralSecurityException)24 X509Certificate (java.security.cert.X509Certificate)24 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)23 DERIA5String (org.bouncycastle.asn1.DERIA5String)22