Example usage for org.bouncycastle.asn1.x509 SubjectKeyIdentifier SubjectKeyIdentifier

List of usage examples for org.bouncycastle.asn1.x509 SubjectKeyIdentifier SubjectKeyIdentifier

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 SubjectKeyIdentifier SubjectKeyIdentifier.

Prototype

protected SubjectKeyIdentifier(ASN1OctetString keyid) 

Source Link

Usage

From source file:org.kopi.ebics.certificate.X509Generator.java

License:Open Source License

/**
 * Returns the <code>SubjectKeyIdentifier</code> corresponding
 * to a given <code>PublicKey</code>
 * @param publicKey the given public key
 * @return the subject key identifier/*from   ww w . ja v a 2 s.c  o m*/
 * @throws IOException
 */
private SubjectKeyIdentifier getSubjectKeyIdentifier(PublicKey publicKey) throws IOException {
    InputStream input;
    SubjectPublicKeyInfo keyInfo;

    input = new ByteArrayInputStream(publicKey.getEncoded());
    keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(input).readObject());

    return new SubjectKeyIdentifier(keyInfo);
}

From source file:org.kse.gui.dialogs.extensions.DSelectStandardExtensionTemplate.java

License:Open Source License

private void addSubjectKeyIdentifier(X509ExtensionSet extensionSet) throws CryptoException, IOException {
    KeyIdentifierGenerator skiGenerator = new KeyIdentifierGenerator(subjectPublicKey);
    SubjectKeyIdentifier ski = new SubjectKeyIdentifier(skiGenerator.generate160BitHashId());
    byte[] skiEncoded = wrapInOctetString(ski.getEncoded());
    extensionSet.addExtension(X509ExtensionType.SUBJECT_KEY_IDENTIFIER.oid(), false, skiEncoded);
}

From source file:org.mailster.gui.dialogs.CertificateDialog.java

License:Open Source License

private void generateExtensionNode(TreeItem parent, X509Certificate cert, X509Extensions extensions,
        String oid) {/*from ww w .  ja  v  a 2s  .c  om*/
    DERObjectIdentifier derOID = new DERObjectIdentifier(oid);
    X509Extension ext = extensions.getExtension(derOID);

    if (ext.getValue() == null)
        return;

    byte[] octs = ext.getValue().getOctets();
    ASN1InputStream dIn = new ASN1InputStream(octs);
    StringBuilder buf = new StringBuilder();

    try {
        if (ext.isCritical())
            buf.append(Messages.getString("MailsterSWT.dialog.certificate.criticalExt")); //$NON-NLS-1$
        else
            buf.append(Messages.getString("MailsterSWT.dialog.certificate.nonCriticalExt")); //$NON-NLS-1$

        if (derOID.equals(X509Extensions.BasicConstraints)) {
            BasicConstraints bc = new BasicConstraints((ASN1Sequence) dIn.readObject());
            if (bc.isCA())
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.BasicConstraints.isCA")); //$NON-NLS-1$
            else
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.BasicConstraints.notCA")); //$NON-NLS-1$

            buf.append(Messages.getString("MailsterSWT.dialog.certificate.BasicConstraints.maxIntermediateCA")); //$NON-NLS-1$

            if (bc.getPathLenConstraint() == null || bc.getPathLenConstraint().intValue() == Integer.MAX_VALUE)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.BasicConstraints.unlimited")); //$NON-NLS-1$
            else
                buf.append(bc.getPathLenConstraint()).append('\n');

            generateNode(parent, Messages.getString(oid), buf);
        } else if (derOID.equals(X509Extensions.KeyUsage)) {
            KeyUsage us = new KeyUsage((DERBitString) dIn.readObject());
            if ((us.intValue() & KeyUsage.digitalSignature) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.digitalSignature")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.nonRepudiation) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.nonRepudiation")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.keyEncipherment) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.keyEncipherment")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.dataEncipherment) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.dataEncipherment")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.keyAgreement) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.keyAgreement")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.keyCertSign) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.keyCertSign")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.cRLSign) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.cRLSign")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.encipherOnly) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.encipherOnly")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.decipherOnly) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.decipherOnly")); //$NON-NLS-1$

            generateNode(parent, Messages.getString(oid), buf);
        } else if (derOID.equals(X509Extensions.SubjectKeyIdentifier)) {
            SubjectKeyIdentifier id = new SubjectKeyIdentifier((DEROctetString) dIn.readObject());
            generateNode(parent, Messages.getString(oid),
                    buf.toString() + CertificateUtilities.byteArrayToString(id.getKeyIdentifier()));
        } else if (derOID.equals(X509Extensions.AuthorityKeyIdentifier)) {
            AuthorityKeyIdentifier id = new AuthorityKeyIdentifier((ASN1Sequence) dIn.readObject());
            generateNode(parent, Messages.getString(oid), buf.toString() + id.getAuthorityCertSerialNumber());
        } else if (derOID.equals(MiscObjectIdentifiers.netscapeRevocationURL)) {
            buf.append(new NetscapeRevocationURL((DERIA5String) dIn.readObject())).append("\n");
            generateNode(parent, Messages.getString(oid), buf.toString());
        } else if (derOID.equals(MiscObjectIdentifiers.verisignCzagExtension)) {
            buf.append(new VerisignCzagExtension((DERIA5String) dIn.readObject())).append("\n");
            generateNode(parent, Messages.getString(oid), buf.toString());
        } else if (derOID.equals(X509Extensions.CRLNumber)) {
            buf.append((DERInteger) dIn.readObject()).append("\n");
            generateNode(parent, Messages.getString(oid), buf.toString());
        } else if (derOID.equals(X509Extensions.ReasonCode)) {
            ReasonFlags rf = new ReasonFlags((DERBitString) dIn.readObject());

            if ((rf.intValue() & ReasonFlags.unused) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.unused")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.keyCompromise) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.keyCompromise")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.cACompromise) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.cACompromise")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.affiliationChanged) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.affiliationChanged")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.superseded) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.superseded")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.cessationOfOperation) > 0)
                buf.append(
                        Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.cessationOfOperation")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.certificateHold) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.certificateHold")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.privilegeWithdrawn) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.privilegeWithdrawn")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.aACompromise) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.aACompromise")); //$NON-NLS-1$
            generateNode(parent, Messages.getString(oid), buf.toString());
        } else if (derOID.equals(MiscObjectIdentifiers.netscapeCertType)) {
            NetscapeCertType type = new NetscapeCertType((DERBitString) dIn.readObject());

            if ((type.intValue() & NetscapeCertType.sslClient) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.sslClient")); //$NON-NLS-1$
            if ((type.intValue() & NetscapeCertType.sslServer) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.sslServer")); //$NON-NLS-1$
            if ((type.intValue() & NetscapeCertType.smime) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.smime")); //$NON-NLS-1$
            if ((type.intValue() & NetscapeCertType.objectSigning) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.objectSigning")); //$NON-NLS-1$
            if ((type.intValue() & NetscapeCertType.reserved) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.reserved")); //$NON-NLS-1$
            if ((type.intValue() & NetscapeCertType.sslCA) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.sslCA")); //$NON-NLS-1$
            if ((type.intValue() & NetscapeCertType.smimeCA) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.smimeCA")); //$NON-NLS-1$
            if ((type.intValue() & NetscapeCertType.objectSigningCA) > 0)
                buf.append(
                        Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.objectSigningCA")); //$NON-NLS-1$

            generateNode(parent, Messages.getString(oid), buf.toString());
        } else if (derOID.equals(X509Extensions.ExtendedKeyUsage)) {
            ExtendedKeyUsage eku = new ExtendedKeyUsage((ASN1Sequence) dIn.readObject());
            if (eku.hasKeyPurposeId(KeyPurposeId.anyExtendedKeyUsage))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.anyExtendedKeyUsage")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth))
                buf.append(
                        Messages.getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_clientAuth")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_codeSigning))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_codeSigning")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_emailProtection))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_emailProtection")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_ipsecEndSystem))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_ipsecEndSystem")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_ipsecTunnel))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_ipsecTunnel")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_ipsecUser))
                buf.append(
                        Messages.getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_ipsecUser")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_OCSPSigning))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_OCSPSigning")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth))
                buf.append(
                        Messages.getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_serverAuth")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_smartcardlogon))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_smartcardlogon")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_timeStamping))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_timeStamping")); //$NON-NLS-1$

            generateNode(parent, Messages.getString(oid), buf.toString());
        } else
            generateNode(parent,
                    MessageFormat.format(Messages.getString("MailsterSWT.dialog.certificate.objectIdentifier"), //$NON-NLS-1$ 
                            new Object[] { oid.replace('.', ' ') }),
                    CertificateUtilities.byteArrayToString((cert.getExtensionValue(oid))));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.nimbustools.auto_common.ezpz_ca.CAFactory.java

License:Apache License

public X509Certificate create(String baseName, int months, KeyPair keyPair) throws Exception {

    final X509Principal newprincipal = new X509Principal("O=Auto,OU=" + baseName + ",CN=CA");

    this.certGen.reset();

    /*// w  ww  .  j  av a2  s.co m
      "The entity that created the certificate is responsible for  assigning
      it a serial number to distinguish it from other certificates it issues.
      This information is used in numerous ways, for example when a
      certificate is revoked its serial number is placed in a Certificate
      Revocation List (CRL)"
    */
    this.certGen.setSerialNumber(BigInteger.ZERO);

    final Calendar expires = Calendar.getInstance();
    expires.add(Calendar.MONTH, months);
    this.certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
    this.certGen.setNotAfter(expires.getTime());

    this.certGen.setSubjectDN(newprincipal);
    this.certGen.setIssuerDN(newprincipal);
    this.certGen.setSignatureAlgorithm("SHA1withRSA");

    final PublicKey pubkey = keyPair.getPublic();
    this.certGen.setPublicKey(pubkey);

    // begin X509/BC security nastiness, not sure these are the very best
    // choices but it is working...

    final ByteArrayInputStream in = new ByteArrayInputStream(pubkey.getEncoded());
    final SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
            (ASN1Sequence) new DERInputStream(in).readObject());
    final SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);

    final ByteArrayInputStream in2 = new ByteArrayInputStream(newprincipal.getEncoded());
    final GeneralNames generalNames = new GeneralNames((ASN1Sequence) new DERInputStream(in2).readObject());
    final AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(spki, generalNames, BigInteger.ZERO);

    this.certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));

    /*
    this.certGen.addExtension(X509Extensions.KeyUsage,
                          true,
                          new KeyUsage(KeyUsage.digitalSignature |
                                       KeyUsage.keyEncipherment));
    */

    this.certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski);

    this.certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki);

    this.certGen.addExtension(X509Extensions.KeyUsage, false,
            new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign));

    return this.certGen.generateX509Certificate(keyPair.getPrivate());
}

From source file:org.objectweb.proactive.core.security.CertTools.java

License:Open Source License

/**
 * DOCUMENT ME!//from  w w w  . ja v  a  2  s  .c om
 *
 * @param dn DOCUMENT ME!
 * @param validity DOCUMENT ME!
 * @param policyId DOCUMENT ME!
 * @param privKey DOCUMENT ME!
 * @param pubKey DOCUMENT ME!
 * @param isCA DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws NoSuchAlgorithmException DOCUMENT ME!
 * @throws SignatureException DOCUMENT ME!
 * @throws InvalidKeyException DOCUMENT ME!
 * @throws IllegalStateException
 * @throws CertificateEncodingException
 */
public static X509Certificate genSelfCert(String dn, long validity, String policyId, PrivateKey privKey,
        PublicKey pubKey, boolean isCA) throws NoSuchAlgorithmException, SignatureException,
        InvalidKeyException, CertificateEncodingException, IllegalStateException {
    // Create self signed certificate
    String sigAlg = "SHA1WithRSA";
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    certgen.setSerialNumber((new java.math.BigInteger(serno)).abs());
    certgen.setNotBefore(firstDate);
    certgen.setNotAfter(lastDate);
    certgen.setSignatureAlgorithm(sigAlg);
    certgen.setSubjectDN(CertTools.stringToBcX509Name(dn));
    certgen.setIssuerDN(CertTools.stringToBcX509Name(dn));
    certgen.setPublicKey(pubKey);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA == true) {
        int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign;
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku);
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Mozilla.
    try {
        if (isCA == true) {
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded()))
                            .readObject());
            SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);

            SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded()))
                            .readObject());
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

            certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski);
            certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki);
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq);
    }

    X509Certificate selfcert = certgen.generate(privKey);

    return selfcert;
}

From source file:org.objectweb.proactive.core.security.CertTools.java

License:Open Source License

public static X509Certificate genCert(String dn, long validity, String policyId, PrivateKey privKey,
        PublicKey pubKey, boolean isCA, String caDn, PrivateKey caPrivateKey, PublicKey acPubKey)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException,
        IllegalStateException {//from   w  w w .j  av a  2  s  . co  m
    // Create self signed certificate
    String sigAlg = "SHA1WithRSA";
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    certgen.setSerialNumber((new java.math.BigInteger(serno)).abs());
    certgen.setNotBefore(firstDate);
    certgen.setNotAfter(lastDate);
    certgen.setSignatureAlgorithm(sigAlg);
    certgen.setSubjectDN(CertTools.stringToBcX509Name(dn));
    certgen.setIssuerDN(CertTools.stringToBcX509Name(caDn));
    certgen.setPublicKey(pubKey);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc);

    // Put critical KeyUsage in CA-certificates
    if (false) {
        //if (isCA == true) {
        int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign;
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku);
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Mozilla.
    try {
        if (false) {
            //if (isCA == true) {
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded()))
                            .readObject());
            SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);

            SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(acPubKey.getEncoded()))
                            .readObject());
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

            certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski);
            certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki);
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq);
    }

    X509Certificate cert = certgen.generate(caPrivateKey);

    return cert;
}

From source file:org.objectweb.proactive.core.security.KeyTools.java

License:Open Source License

/**
 * create the subject key identifier./*from w w  w .java 2s . c  o  m*/
 *
 * @param pubKey the public key
 *
 * @return SubjectKeyIdentifer asn.1 structure
 */
public static SubjectKeyIdentifier createSubjectKeyId(PublicKey pubKey) {
    try {
        ByteArrayInputStream bIn = new ByteArrayInputStream(pubKey.getEncoded());
        SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(bIn).readObject());

        return new SubjectKeyIdentifier(info);
    } catch (Exception e) {
        throw new RuntimeException("error creating key");
    }
}

From source file:org.opcfoundation.ua.utils.CertificateUtils.java

License:Open Source License

/**
 * /*from   ww w  .ja  v a 2  s.  c o m*/
 * @param commonName - Common Name (CN) for generated certificate
 * @param organisation - Organisation (O) for generated certificate
 * @param applicationUri - Alternative name (one of x509 extensiontype) for generated certificate. Must not be null
 * @param validityTime - the time that the certificate is valid (in days)
 * @return
 * @throws IOException
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 * @throws InvalidKeyException
 * @throws IllegalStateException
 * @throws NoSuchProviderException
 * @throws SignatureException
 * @throws CertificateParsingException
 */
public static org.opcfoundation.ua.transport.security.KeyPair createApplicationInstanceCertificate(
        String commonName, String organisation, String applicationUri, int validityTime) throws IOException,
        InvalidKeySpecException, NoSuchAlgorithmException, CertificateEncodingException, InvalidKeyException,
        IllegalStateException, NoSuchProviderException, SignatureException, CertificateParsingException {
    if (applicationUri == null)
        throw new NullPointerException("applicationUri must not be null");
    //Add provider for generator
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    //Initializes generator 
    SecureRandom srForCert = new SecureRandom();
    RSAKeyPairGenerator genForCert = new RSAKeyPairGenerator();

    //Used for generating prime
    Random r = new Random(System.currentTimeMillis());
    int random = -1;

    while (random < 3) {
        random = r.nextInt(32);
    }
    //calculate(generate) possible value for public modulus
    //used method is "monte carlo -algorithm", so we calculate it as long as it generates value.
    BigInteger value = null;
    while (value == null) {
        value = BigInteger.probablePrime(random, new SecureRandom());
    }

    //Generate (Java) keypair
    genForCert.init(new RSAKeyGenerationParameters(value, srForCert, KEY_SIZE, 80));
    AsymmetricCipherKeyPair keypairForCert = genForCert.generateKeyPair();

    //Extract the keys from parameters
    logger.debug("Generated keypair, extracting components and creating public structure for certificate");
    RSAKeyParameters clientPublicKey = (RSAKeyParameters) keypairForCert.getPublic();
    RSAPrivateCrtKeyParameters clientPrivateKey = (RSAPrivateCrtKeyParameters) keypairForCert.getPrivate();
    // used to get proper encoding for the certificate
    RSAPublicKeyStructure clientPkStruct = new RSAPublicKeyStructure(clientPublicKey.getModulus(),
            clientPublicKey.getExponent());
    logger.debug("New public key is '" + makeHexString(clientPkStruct.getEncoded()) + ", exponent="
            + clientPublicKey.getExponent() + ", modulus=" + clientPublicKey.getModulus());

    // JCE format needed for the certificate - because getEncoded() is necessary...
    PublicKey certPubKey = KeyFactory.getInstance("RSA")
            .generatePublic(new RSAPublicKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent()));
    // and this one for the KeyStore
    PrivateKey certPrivKey = KeyFactory.getInstance("RSA").generatePrivate(
            new RSAPrivateCrtKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent(),
                    clientPrivateKey.getExponent(), clientPrivateKey.getP(), clientPrivateKey.getQ(),
                    clientPrivateKey.getDP(), clientPrivateKey.getDQ(), clientPrivateKey.getQInv()));

    //The data for the certificate..
    Calendar expiryTime = Calendar.getInstance();
    expiryTime.add(Calendar.DAY_OF_YEAR, validityTime);

    X509Name certificateX509Name = new X509Name(
            "CN=" + commonName + ", O=" + organisation + ", C=" + System.getProperty("user.country"));

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
    certGen.setSerialNumber(serial);
    //Issuer and subject must be the same (because this is self signed)
    certGen.setIssuerDN(certificateX509Name);
    certGen.setSubjectDN(certificateX509Name);

    //expiry & start time for this certificate
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000 * 60 * 60)); //take 60 minutes (1000 ms * 60 s * 60) away from system clock (in case there is some lag in system clocks)
    certGen.setNotAfter(expiryTime.getTime());

    certGen.setPublicKey(certPubKey);
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    //******* X.509 V3 Extensions *****************

    SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
            (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(certPubKey.getEncoded())).readObject());
    SubjectKeyIdentifier ski = new SubjectKeyIdentifier(apki);

    /*certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true,
    new DEROctetString(ski//new SubjectKeyIdentifier Structure(apki/*certPubKey)));
        */
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski);
    certGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            /*new DEROctetString(new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign ))*/new KeyUsage(
                    KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation
                            | KeyUsage.dataEncipherment | KeyUsage.keyCertSign));

    BasicConstraints b = new BasicConstraints(false);

    Vector<KeyPurposeId> extendedKeyUsages = new Vector<KeyPurposeId>();
    extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth);
    extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth);
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            /*new DEROctetString(new ExtendedKeyUsage(extendedKeyUsages))*/new ExtendedKeyUsage(
                    extendedKeyUsages));

    // create the extension value
    ASN1EncodableVector names = new ASN1EncodableVector();
    names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri));
    //      GeneralName dnsName = new GeneralName(GeneralName.dNSName, applicationUri);
    //      names.add(dnsName);
    final GeneralNames subjectAltNames = new GeneralNames(new DERSequence(names));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, true, subjectAltNames);

    // AuthorityKeyIdentifier

    final GeneralNames certificateIssuer = new GeneralNames(new GeneralName(certificateX509Name));
    AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki, certificateIssuer, serial);

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki);
    //***** generate certificate ***********/
    X509Certificate cert = certGen.generate(certPrivKey, "BC");

    //Encapsulate Certificate and private key to CertificateKeyPair
    Cert certificate = new Cert(cert);
    org.opcfoundation.ua.transport.security.PrivKey UAkey = new org.opcfoundation.ua.transport.security.PrivKey(
            (RSAPrivateKey) certPrivKey);
    return new org.opcfoundation.ua.transport.security.KeyPair(certificate, UAkey);
}

From source file:org.openmaji.implementation.security.utility.cert.CertUtil.java

License:Open Source License

private static SubjectKeyIdentifier createSubjectKeyId(PublicKey pubKey) {
    try {//ww  w .j  a  v a  2 s  .  co  m
        ByteArrayInputStream bIn = new ByteArrayInputStream(pubKey.getEncoded());
        SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(bIn).readObject());
        //                (ASN1Sequence)new DERInputStream(bIn).readObject());

        return new SubjectKeyIdentifier(info);
    } catch (Exception e) {
        throw new RuntimeException("error creating key");
    }
}

From source file:org.openmaji.implementation.server.security.auth.CoreAdminHelper.java

License:Open Source License

private static SubjectKeyIdentifier createSubjectKeyId(PublicKey pubKey) {
    try {/*from w  ww .  ja v a2s . c o m*/
        ByteArrayInputStream bIn = new ByteArrayInputStream(pubKey.getEncoded());
        SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(bIn).readObject());

        return new SubjectKeyIdentifier(info);
    } catch (Exception e) {
        throw new RuntimeException("error creating key");
    }
}