Search in sources :

Example 16 with PKCS10

use of sun.security.pkcs10.PKCS10 in project Bytecoder by mirkosertic.

the class Pair method doGenCert.

/**
 * Generate a certificate: Read PKCS10 request from in, and print
 * certificate to out. Use alias as CA, sigAlgName as the signature
 * type.
 */
private void doGenCert(String alias, String sigAlgName, InputStream in, PrintStream out) throws Exception {
    if (keyStore.containsAlias(alias) == false) {
        MessageFormat form = new MessageFormat(rb.getString("Alias.alias.does.not.exist"));
        Object[] source = { alias };
        throw new Exception(form.format(source));
    }
    Certificate signerCert = keyStore.getCertificate(alias);
    byte[] encoded = signerCert.getEncoded();
    X509CertImpl signerCertImpl = new X509CertImpl(encoded);
    X509CertInfo signerCertInfo = (X509CertInfo) signerCertImpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO);
    X500Name issuer = (X500Name) signerCertInfo.get(X509CertInfo.SUBJECT + "." + X509CertInfo.DN_NAME);
    Date firstDate = getStartDate(startDate);
    Date lastDate = new Date();
    lastDate.setTime(firstDate.getTime() + validity * 1000L * 24L * 60L * 60L);
    CertificateValidity interval = new CertificateValidity(firstDate, lastDate);
    PrivateKey privateKey = (PrivateKey) recoverKey(alias, storePass, keyPass).fst;
    if (sigAlgName == null) {
        sigAlgName = getCompatibleSigAlgName(privateKey);
    }
    Signature signature = Signature.getInstance(sigAlgName);
    signature.initSign(privateKey);
    X509CertInfo info = new X509CertInfo();
    info.set(X509CertInfo.VALIDITY, interval);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new java.util.Random().nextInt() & 0x7fffffff));
    info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
    info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(AlgorithmId.get(sigAlgName)));
    info.set(X509CertInfo.ISSUER, issuer);
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    boolean canRead = false;
    StringBuffer sb = new StringBuffer();
    while (true) {
        String s = reader.readLine();
        if (s == null)
            break;
        // if (s.startsWith("-----BEGIN NEW CERTIFICATE REQUEST-----")) {
        if (s.startsWith("-----BEGIN") && s.indexOf("REQUEST") >= 0) {
            canRead = true;
        // } else if (s.startsWith("-----END NEW CERTIFICATE REQUEST-----")) {
        } else if (s.startsWith("-----END") && s.indexOf("REQUEST") >= 0) {
            break;
        } else if (canRead) {
            sb.append(s);
        }
    }
    byte[] rawReq = Pem.decode(new String(sb));
    PKCS10 req = new PKCS10(rawReq);
    checkWeak(rb.getString("the.certificate.request"), req);
    info.set(X509CertInfo.KEY, new CertificateX509Key(req.getSubjectPublicKeyInfo()));
    info.set(X509CertInfo.SUBJECT, dname == null ? req.getSubjectName() : new X500Name(dname));
    CertificateExtensions reqex = null;
    Iterator<PKCS10Attribute> attrs = req.getAttributes().getAttributes().iterator();
    while (attrs.hasNext()) {
        PKCS10Attribute attr = attrs.next();
        if (attr.getAttributeId().equals(PKCS9Attribute.EXTENSION_REQUEST_OID)) {
            reqex = (CertificateExtensions) attr.getAttributeValue();
        }
    }
    CertificateExtensions ext = createV3Extensions(reqex, null, v3ext, req.getSubjectPublicKeyInfo(), signerCert.getPublicKey());
    info.set(X509CertInfo.EXTENSIONS, ext);
    X509CertImpl cert = new X509CertImpl(info);
    cert.sign(privateKey, sigAlgName);
    dumpCert(cert, out);
    for (Certificate ca : keyStore.getCertificateChain(alias)) {
        if (ca instanceof X509Certificate) {
            X509Certificate xca = (X509Certificate) ca;
            if (!KeyStoreUtil.isSelfSigned(xca)) {
                dumpCert(xca, out);
            }
        }
    }
    checkWeak(rb.getString("the.issuer"), keyStore.getCertificateChain(alias));
    checkWeak(rb.getString("the.generated.certificate"), cert);
}
Also used : PKCS10Attribute(sun.security.pkcs10.PKCS10Attribute) PrivateKey(java.security.PrivateKey) PKCS10(sun.security.pkcs10.PKCS10) MessageFormat(java.text.MessageFormat) KeyStoreException(java.security.KeyStoreException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) CertStoreException(java.security.cert.CertStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate) Signature(java.security.Signature) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 17 with PKCS10

use of sun.security.pkcs10.PKCS10 in project Bytecoder by mirkosertic.

the class Pair method doCertReq.

/**
 * Creates a PKCS#10 cert signing request, corresponding to the
 * keys (and name) associated with a given alias.
 */
private void doCertReq(String alias, String sigAlgName, PrintStream out) throws Exception {
    if (alias == null) {
        alias = keyAlias;
    }
    Pair<Key, char[]> objs = recoverKey(alias, storePass, keyPass);
    PrivateKey privKey = (PrivateKey) objs.fst;
    if (keyPass == null) {
        keyPass = objs.snd;
    }
    Certificate cert = keyStore.getCertificate(alias);
    if (cert == null) {
        MessageFormat form = new MessageFormat(rb.getString("alias.has.no.public.key.certificate."));
        Object[] source = { alias };
        throw new Exception(form.format(source));
    }
    PKCS10 request = new PKCS10(cert.getPublicKey());
    CertificateExtensions ext = createV3Extensions(null, null, v3ext, cert.getPublicKey(), null);
    // Attribute name is not significant
    request.getAttributes().setAttribute(X509CertInfo.EXTENSIONS, new PKCS10Attribute(PKCS9Attribute.EXTENSION_REQUEST_OID, ext));
    // Construct a Signature object, so that we can sign the request
    if (sigAlgName == null) {
        sigAlgName = getCompatibleSigAlgName(privKey);
    }
    Signature signature = Signature.getInstance(sigAlgName);
    signature.initSign(privKey);
    X500Name subject = dname == null ? new X500Name(((X509Certificate) cert).getSubjectDN().toString()) : new X500Name(dname);
    // Sign the request and base-64 encode it
    request.encodeAndSign(subject, signature);
    request.print(out);
    checkWeak(rb.getString("the.generated.certificate.request"), request);
}
Also used : PKCS10Attribute(sun.security.pkcs10.PKCS10Attribute) PrivateKey(java.security.PrivateKey) MessageFormat(java.text.MessageFormat) KeyStoreException(java.security.KeyStoreException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) CertStoreException(java.security.cert.CertStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) PKCS10(sun.security.pkcs10.PKCS10) Signature(java.security.Signature) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) PublicKey(java.security.PublicKey) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 18 with PKCS10

use of sun.security.pkcs10.PKCS10 in project spring-cloud-digital-sign by SpringForAll.

the class PfxCertStoreUtils method generateCSR.

public String generateCSR(String alg, int size, String cn) {
    Security.addProvider(new BouncyCastleProvider());
    String strCSR = "";
    try {
        strCSR = "";
        String sigAlg = "SHA1WithRSA";
        if ((alg == null) || (alg.length() <= 0))
            sigAlg = "SHA1WithRSA";
        else
            sigAlg = alg;
        int algSize = 1024;
        if (size != 0)
            algSize = size;
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(algSize, new SecureRandom());
        this.kp = kpg.generateKeyPair();
        PublicKey publicKey = this.kp.getPublic();
        PrivateKey privateKey = this.kp.getPrivate();
        PKCS10 pkcs10 = new PKCS10(publicKey);
        Signature signature = Signature.getInstance(sigAlg);
        signature.initSign(privateKey);
        String CN = "defaultUserName";
        if ((cn != null) && (cn.length() > 0))
            CN = cn;
        String DN = "CN=" + CN + ",C=CN";
        X500Name x500Name = new X500Name(DN);
        pkcs10.encodeAndSign(x500Name, signature);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        pkcs10.print(ps);
        String strPEMCSR = baos.toString();
        strCSR = strPEMCSR.replaceAll("\r|\n", "");
        strCSR = strCSR.replaceAll("-----BEGIN NEW CERTIFICATE REQUEST-----", "");
        strCSR = strCSR.replaceAll("-----END NEW CERTIFICATE REQUEST-----", "");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
        return null;
    }
    return strCSR;
}
Also used : PrintStream(java.io.PrintStream) CertificateException(java.security.cert.CertificateException) X500Name(sun.security.x509.X500Name) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) PKCS10(sun.security.pkcs10.PKCS10) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 19 with PKCS10

use of sun.security.pkcs10.PKCS10 in project spring-cloud-digital-sign by SpringForAll.

the class PfxCertStoreUtils method generateCSR.

public String generateCSR(String alg, int size, String cn) {
    Security.addProvider(new BouncyCastleProvider());
    String strCSR = "";
    try {
        strCSR = "";
        String sigAlg = "SHA1WithRSA";
        if ((alg == null) || (alg.length() <= 0))
            sigAlg = "SHA1WithRSA";
        else
            sigAlg = alg;
        int algSize = 1024;
        if (size != 0)
            algSize = size;
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(algSize, new SecureRandom());
        this.kp = kpg.generateKeyPair();
        PublicKey publicKey = this.kp.getPublic();
        PrivateKey privateKey = this.kp.getPrivate();
        PKCS10 pkcs10 = new PKCS10(publicKey);
        Signature signature = Signature.getInstance(sigAlg);
        signature.initSign(privateKey);
        String CN = "defaultUserName";
        if ((cn != null) && (cn.length() > 0))
            CN = cn;
        String DN = "CN=" + CN + ",C=CN";
        X500Name x500Name = new X500Name(DN);
        pkcs10.encodeAndSign(x500Name, signature);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        pkcs10.print(ps);
        String strPEMCSR = baos.toString();
        strCSR = strPEMCSR.replaceAll("\r|\n", "");
        strCSR = strCSR.replaceAll("-----BEGIN NEW CERTIFICATE REQUEST-----", "");
        strCSR = strCSR.replaceAll("-----END NEW CERTIFICATE REQUEST-----", "");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
        return null;
    }
    return strCSR;
}
Also used : PrintStream(java.io.PrintStream) CertificateException(java.security.cert.CertificateException) X500Name(sun.security.x509.X500Name) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) PKCS10(sun.security.pkcs10.PKCS10) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 20 with PKCS10

use of sun.security.pkcs10.PKCS10 in project serverpacklocator by cpw.

the class CertificateManager method generateCSR.

public static void generateCSR(Supplier<String> canonicalName, Supplier<KeyPair> keySupplier, Consumer<PKCS10> csrConsumer) {
    PKCS10 pkcs10;
    try {
        X500Name name = new X500Name("CN=" + canonicalName.get());
        final Signature sha256WithRSA = Signature.getInstance("SHA256WithRSA");
        sha256WithRSA.initSign(keySupplier.get().getPrivate(), RANDOM);
        pkcs10 = new PKCS10(keySupplier.get().getPublic());
        pkcs10.encodeAndSign(name, sha256WithRSA);
        LOGGER.debug("Generated new CSR with name {}", name.getCommonName());
    } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | CertificateException | SignatureException e) {
        LOGGER.catching(e);
        throw new RuntimeException("Failed to generate CSR", e);
    }
    csrConsumer.accept(pkcs10);
}
Also used : PKCS10(sun.security.pkcs10.PKCS10)

Aggregations

PKCS10 (sun.security.pkcs10.PKCS10)19 CertificateException (java.security.cert.CertificateException)11 IOException (java.io.IOException)8 PKCS10Attribute (sun.security.pkcs10.PKCS10Attribute)8 PrivateKey (java.security.PrivateKey)5 Signature (java.security.Signature)5 X509Certificate (java.security.cert.X509Certificate)5 X500Name (sun.security.x509.X500Name)5 PublicKey (java.security.PublicKey)4 Certificate (java.security.cert.Certificate)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 PrintStream (java.io.PrintStream)3 KeyStoreException (java.security.KeyStoreException)3 UnrecoverableEntryException (java.security.UnrecoverableEntryException)3 UnrecoverableKeyException (java.security.UnrecoverableKeyException)3 CertStoreException (java.security.cert.CertStoreException)3 MessageFormat (java.text.MessageFormat)3 BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)3 ObjectIdentifier (sun.security.util.ObjectIdentifier)3 Key (java.security.Key)2