Search in sources :

Example 71 with X500Name

use of org.bouncycastle.asn1.x500.X500Name in project jdk8u_jdk by JetBrains.

the class X509CertSelectorTest method testPathToName.

/*
     * Tests matching on the name constraints extension contained in the
     * certificate.
     */
private void testPathToName() throws IOException {
    System.out.println("X.509 Certificate Match on pathToName");
    X509CertSelector selector = null;
    DerInputStream in = new DerInputStream(cert.getExtensionValue("2.5.29.30"));
    byte[] encoded = in.getOctetString();
    NameConstraintsExtension ext = new NameConstraintsExtension(false, encoded);
    GeneralSubtrees permitted = (GeneralSubtrees) ext.get(PERMITTED_SUBTREES);
    GeneralSubtrees excluded = (GeneralSubtrees) ext.get(EXCLUDED_SUBTREES);
    // bad matches on pathToName within excluded subtrees
    if (excluded != null) {
        Iterator<GeneralSubtree> e = excluded.iterator();
        while (e.hasNext()) {
            GeneralSubtree tree = e.next();
            if (tree.getName().getType() == NAME_DIRECTORY) {
                X500Name excludedDN1 = new X500Name(tree.getName().toString());
                X500Name excludedDN2 = new X500Name("CN=Bogus, " + tree.getName().toString());
                DerOutputStream derDN1 = new DerOutputStream();
                DerOutputStream derDN2 = new DerOutputStream();
                excludedDN1.encode(derDN1);
                excludedDN2.encode(derDN2);
                selector = new X509CertSelector();
                selector.addPathToName(NAME_DIRECTORY, derDN1.toByteArray());
                checkMatch(selector, cert, false);
                selector.setPathToNames(null);
                selector.addPathToName(NAME_DIRECTORY, derDN2.toByteArray());
                checkMatch(selector, cert, false);
            }
        }
    }
    // good matches on pathToName within permitted subtrees
    if (permitted != null) {
        Iterator<GeneralSubtree> e = permitted.iterator();
        while (e.hasNext()) {
            GeneralSubtree tree = e.next();
            if (tree.getName().getType() == NAME_DIRECTORY) {
                X500Name permittedDN1 = new X500Name(tree.getName().toString());
                X500Name permittedDN2 = new X500Name("CN=good, " + tree.getName().toString());
                DerOutputStream derDN1 = new DerOutputStream();
                DerOutputStream derDN2 = new DerOutputStream();
                permittedDN1.encode(derDN1);
                permittedDN2.encode(derDN2);
                selector = new X509CertSelector();
                selector.addPathToName(NAME_DIRECTORY, derDN1.toByteArray());
                checkMatch(selector, cert, true);
                selector.setPathToNames(null);
                selector.addPathToName(NAME_DIRECTORY, derDN2.toByteArray());
                checkMatch(selector, cert, true);
            }
        }
    }
}
Also used : DerOutputStream(sun.security.util.DerOutputStream) GeneralSubtrees(sun.security.x509.GeneralSubtrees) X509CertSelector(java.security.cert.X509CertSelector) DerInputStream(sun.security.util.DerInputStream) NameConstraintsExtension(sun.security.x509.NameConstraintsExtension) GeneralSubtree(sun.security.x509.GeneralSubtree) X500Name(sun.security.x509.X500Name)

Example 72 with X500Name

use of org.bouncycastle.asn1.x500.X500Name in project jdk8u_jdk by JetBrains.

the class PKCS12SameKeyId method main.

public static void main(String[] args) throws Exception {
    // Prepare a JKS keystore with many entries
    new File(JKSFILE).delete();
    for (int i = 0; i < SIZE; i++) {
        System.err.print(".");
        String cmd = "-keystore " + JKSFILE + " -storepass changeit -keypass changeit -keyalg rsa " + "-genkeypair -alias p" + i + " -dname CN=" + i;
        sun.security.tools.keytool.Main.main(cmd.split(" "));
    }
    // Prepare EncryptedPrivateKeyInfo parameters, copied from various
    // places in PKCS12KeyStore.java
    AlgorithmParameters algParams = AlgorithmParameters.getInstance("PBEWithSHA1AndDESede");
    algParams.init(new PBEParameterSpec("12345678".getBytes(), 1024));
    AlgorithmId algid = new AlgorithmId(new ObjectIdentifier("1.2.840.113549.1.12.1.3"), algParams);
    PBEKeySpec keySpec = new PBEKeySpec(PASSWORD);
    SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
    SecretKey skey = skFac.generateSecret(keySpec);
    Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
    cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
    // Pre-calculated keys and certs and aliases
    byte[][] keys = new byte[SIZE][];
    Certificate[][] certChains = new Certificate[SIZE][];
    String[] aliases = new String[SIZE];
    // Reads from JKS keystore and pre-calculate
    KeyStore ks = KeyStore.getInstance("jks");
    try (FileInputStream fis = new FileInputStream(JKSFILE)) {
        ks.load(fis, PASSWORD);
    }
    for (int i = 0; i < SIZE; i++) {
        aliases[i] = "p" + i;
        byte[] enckey = cipher.doFinal(ks.getKey(aliases[i], PASSWORD).getEncoded());
        keys[i] = new EncryptedPrivateKeyInfo(algid, enckey).getEncoded();
        certChains[i] = ks.getCertificateChain(aliases[i]);
    }
    // Write into PKCS12 keystore. Use this overloaded version of
    // setKeyEntry() to be as fast as possible, so that they would
    // have same localKeyId.
    KeyStore p12 = KeyStore.getInstance("pkcs12");
    p12.load(null, PASSWORD);
    for (int i = 0; i < SIZE; i++) {
        p12.setKeyEntry(aliases[i], keys[i], certChains[i]);
    }
    try (FileOutputStream fos = new FileOutputStream(P12FILE)) {
        p12.store(fos, PASSWORD);
    }
    // Check private keys still match certs
    p12 = KeyStore.getInstance("pkcs12");
    try (FileInputStream fis = new FileInputStream(P12FILE)) {
        p12.load(fis, PASSWORD);
    }
    for (int i = 0; i < SIZE; i++) {
        String a = "p" + i;
        X509Certificate x = (X509Certificate) p12.getCertificate(a);
        X500Name name = (X500Name) x.getSubjectDN();
        if (!name.getCommonName().equals("" + i)) {
            throw new Exception(a + "'s cert is " + name);
        }
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) X500Name(sun.security.x509.X500Name) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) SecretKey(javax.crypto.SecretKey) AlgorithmId(sun.security.x509.AlgorithmId) FileOutputStream(java.io.FileOutputStream) EncryptedPrivateKeyInfo(sun.security.pkcs.EncryptedPrivateKeyInfo) Cipher(javax.crypto.Cipher) File(java.io.File) SecretKeyFactory(javax.crypto.SecretKeyFactory) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) AlgorithmParameters(java.security.AlgorithmParameters) ObjectIdentifier(sun.security.util.ObjectIdentifier) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 73 with X500Name

use of org.bouncycastle.asn1.x500.X500Name in project jdk8u_jdk by JetBrains.

the class SmallPrimeExponentP method main.

public static void main(String[] argv) throws Exception {
    String osName = System.getProperty("os.name");
    if (!osName.startsWith("Windows")) {
        System.out.println("Not windows");
        return;
    }
    KeyStore ks = KeyStore.getInstance("Windows-MY");
    ks.load(null, null);
    CertAndKeyGen ckg = new CertAndKeyGen("RSA", "SHA1withRSA");
    ckg.setRandom(new SecureRandom());
    boolean see63 = false, see65 = false;
    while (!see63 || !see65) {
        ckg.generate(1024);
        RSAPrivateCrtKey k = (RSAPrivateCrtKey) ckg.getPrivateKey();
        int len = k.getPrimeExponentP().toByteArray().length;
        if (len == 63 || len == 65) {
            if (len == 63) {
                if (see63)
                    continue;
                else
                    see63 = true;
            }
            if (len == 65) {
                if (see65)
                    continue;
                else
                    see65 = true;
            }
            System.err.print(len);
            ks.setKeyEntry("anything", k, null, new X509Certificate[] { ckg.getSelfCertificate(new X500Name("CN=Me"), 1000) });
        }
        System.err.print('.');
    }
    ks.store(null, null);
}
Also used : RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey) CertAndKeyGen(sun.security.tools.keytool.CertAndKeyGen) SecureRandom(java.security.SecureRandom) X500Name(sun.security.x509.X500Name) KeyStore(java.security.KeyStore)

Example 74 with X500Name

use of org.bouncycastle.asn1.x500.X500Name in project jdk8u_jdk by JetBrains.

the class PKCS10AttrEncoding method main.

public static void main(String[] args) throws Exception {
    // initializations
    int len = ids.length;
    Object[] values = { new ObjectIdentifier("1.2.3.4"), new GregorianCalendar(1970, 1, 25, 8, 56, 7).getTime(), "challenging" };
    for (int j = 0; j < len; j++) {
        constructedMap.put(ids[j], values[j]);
    }
    X500Name subject = new X500Name("cn=Test");
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
    String sigAlg = "DSA";
    keyGen.initialize(512);
    KeyPair pair = keyGen.generateKeyPair();
    X509Key publicKey = (X509Key) pair.getPublic();
    PrivateKey privateKey = pair.getPrivate();
    Signature signature = Signature.getInstance(sigAlg);
    signature.initSign(privateKey);
    // Create the PKCS10 request
    PKCS10Attribute[] attrs = new PKCS10Attribute[len];
    for (int j = 0; j < len; j++) {
        attrs[j] = new PKCS10Attribute(ids[j], values[j]);
    }
    PKCS10 req = new PKCS10(publicKey, new PKCS10Attributes(attrs));
    System.out.println("List of attributes in constructed PKCS10 " + "request: ");
    checkAttributes(req.getAttributes().getElements());
    // Encode the PKCS10 request and generate another PKCS10 request from
    // the encoded byte array
    req.encodeAndSign(subject, signature);
    PKCS10 resp = new PKCS10(req.getEncoded());
    System.out.println("List of attributes in DER encoded PKCS10 Request:");
    checkAttributes(resp.getAttributes().getElements());
    if (failedCount > 0) {
        throw new RuntimeException("Attributes Compared : Failed");
    }
    System.out.println("Attributes Compared : Pass");
}
Also used : PKCS10Attribute(sun.security.pkcs10.PKCS10Attribute) KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PKCS10Attributes(sun.security.pkcs10.PKCS10Attributes) GregorianCalendar(java.util.GregorianCalendar) X500Name(sun.security.x509.X500Name) KeyPairGenerator(java.security.KeyPairGenerator) X509Key(sun.security.x509.X509Key) PKCS10(sun.security.pkcs10.PKCS10) Signature(java.security.Signature) ObjectIdentifier(sun.security.util.ObjectIdentifier)

Example 75 with X500Name

use of org.bouncycastle.asn1.x500.X500Name in project jdk8u_jdk by JetBrains.

the class NonStandardNames method main.

public static void main(String[] args) throws Exception {
    byte[] data = "Hello".getBytes();
    X500Name n = new X500Name("cn=Me");
    CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
    cakg.generate(1024);
    X509Certificate cert = cakg.getSelfCertificate(n, 1000);
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[] { new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID), new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)) });
    Signature s = Signature.getInstance("SHA256withRSA");
    s.initSign(cakg.getPrivateKey());
    s.update(authed.getDerEncoding());
    byte[] sig = s.sign();
    SignerInfo signerInfo = new SignerInfo(n, cert.getSerialNumber(), AlgorithmId.get("SHA-256"), authed, AlgorithmId.get("SHA256withRSA"), sig, null);
    PKCS7 pkcs7 = new PKCS7(new AlgorithmId[] { signerInfo.getDigestAlgorithmId() }, new ContentInfo(data), new X509Certificate[] { cert }, new SignerInfo[] { signerInfo });
    if (pkcs7.verify(signerInfo, data) == null) {
        throw new Exception("Not verified");
    }
}
Also used : SignerInfo(sun.security.pkcs.SignerInfo) PKCS9Attribute(sun.security.pkcs.PKCS9Attribute) ContentInfo(sun.security.pkcs.ContentInfo) PKCS7(sun.security.pkcs.PKCS7) CertAndKeyGen(sun.security.tools.keytool.CertAndKeyGen) Signature(java.security.Signature) X500Name(sun.security.x509.X500Name) MessageDigest(java.security.MessageDigest) PKCS9Attributes(sun.security.pkcs.PKCS9Attributes) X509Certificate(java.security.cert.X509Certificate)

Aggregations

X500Name (org.bouncycastle.asn1.x500.X500Name)54 X509Certificate (java.security.cert.X509Certificate)39 X500Name (sun.security.x509.X500Name)30 IOException (java.io.IOException)23 Date (java.util.Date)22 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)20 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)19 BigInteger (java.math.BigInteger)18 SecureRandom (java.security.SecureRandom)16 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)16 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)15 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)15 KeyPair (java.security.KeyPair)12 PrivateKey (java.security.PrivateKey)12 CertificateEncodingException (java.security.cert.CertificateEncodingException)12 RDN (org.bouncycastle.asn1.x500.RDN)12 ContentSigner (org.bouncycastle.operator.ContentSigner)12 KeyStore (java.security.KeyStore)11 ArrayList (java.util.ArrayList)10 GeneralName (org.bouncycastle.asn1.x509.GeneralName)10