Example usage for org.bouncycastle.jce X509Principal getEncoded

List of usage examples for org.bouncycastle.jce X509Principal getEncoded

Introduction

In this page you can find the example usage for org.bouncycastle.jce X509Principal getEncoded.

Prototype

public byte[] getEncoded() 

Source Link

Document

return a DER encoded byte array representing this object

Usage

From source file:be.fedict.trust.service.bean.CertificateAuthorityLookupBean.java

License:Open Source License

private void refreshLookupMap() throws CertificateEncodingException, NoSuchAlgorithmException {
    LOG.debug("refreshing lookup map");
    List<CertificateAuthorityEntity> activeCertificateAuthorities = this.certificateAuthorityDAO
            .listActiveCertificateAuthorities();
    Map<String, String> freshLookupMap = new HashMap<String, String>();
    for (CertificateAuthorityEntity certificateAuthority : activeCertificateAuthorities) {
        X509Certificate caCert = certificateAuthority.getCertificate();
        X509Principal issuerName = PrincipalUtil.getSubjectX509Principal(caCert);
        byte[] issuerNameHash = getHash(issuerName.getEncoded());
        String caNameHashKey = Hex.encodeHexString(issuerNameHash);
        String caName = caCert.getSubjectX500Principal().toString();
        freshLookupMap.put(caNameHashKey, caName);
        LOG.debug("lookup entry: " + caNameHashKey + " = " + caName);

    }/*from   w  w  w .ja v a 2 s .co  m*/
    this.lookupMap = freshLookupMap; // concurrency is no problem here
}

From source file:ee.sk.digidoc.factory.BouncyCastleNotaryFactory.java

License:Open Source License

/**
* Method for creating CertificateID for OCSP request
* @param signersCert//  w  ww  .  j ava2s .  c o m
* @param caCert
* @param provider
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws CertificateEncodingException
*/
private CertificateID creatCertReq(X509Certificate signersCert, X509Certificate caCert)
        throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException,
        DigiDocException {
    // TODO: checks this OID !!!
    MessageDigest digest = MessageDigest.getInstance("1.3.14.3.2.26", "BC");
    if (m_logger.isDebugEnabled())
        m_logger.debug("CA cert: " + ((caCert != null) ? caCert.toString() : "NULL"));
    X509Principal issuerName = PrincipalUtil.getSubjectX509Principal(caCert);
    if (m_logger.isDebugEnabled())
        m_logger.debug("CA issuer: " + ((issuerName != null) ? issuerName.getName() : "NULL"));
    //Issuer name hash
    digest.update(issuerName.getEncoded());
    ASN1OctetString issuerNameHash = new BERConstructedOctetString(digest.digest());

    //Issuer key hash will be readed out from X509extendions
    // 4 first bytes are not useful for me, oid 2.5.29.15 contains keyid
    byte[] arr = caCert.getExtensionValue("2.5.29.14");
    if (m_logger.isDebugEnabled())
        m_logger.debug("Issuer key hash: " + ((arr != null) ? arr.length : 0));
    if (arr == null || arr.length == 0)
        throw new DigiDocException(DigiDocException.ERR_CA_CERT_READ,
                "CA certificate has no SubjectKeyIdentifier extension!", null);
    byte[] arr2 = new byte[arr.length - 4];
    System.arraycopy(arr, 4, arr2, 0, arr2.length);
    ASN1OctetString issuerKeyHash = new BERConstructedOctetString(arr2);

    CertID cerid = new CertID(new AlgorithmIdentifier("1.3.14.3.2.26"), issuerNameHash, issuerKeyHash,
            new DERInteger(signersCert.getSerialNumber()));
    return new CertificateID(cerid);
}

From source file:net.jxta.impl.membership.pse.PSEUtils.java

License:Open Source License

/**
 * Generate a Cert/*from   w  w  w  .  jav a2  s  . c  o  m*/
 *
 * @param cn         subject cn for the certificate
 * @param issuerinfo the cert issuer or null if self-signed root cert.
 * @return the details of the generated cert.
 * @throws SecurityException if the cert could not be generated.
 */
public static IssuerInfo genCert(String cn, IssuerInfo issuerinfo) throws SecurityException {

    try {

        String useCN;

        if (null == issuerinfo) {

            Logging.logCheckedFine(LOG, "Generating Self Signed Cert ...");

            if (!cn.endsWith("-CA")) {
                useCN = cn + "-CA";
            } else {
                useCN = cn;
            }

        } else {

            Logging.logCheckedFine(LOG, "Generating Client Cert ...");
            useCN = cn;

        }

        // set name attribute
        Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>();

        attrs.put(X509Principal.CN, useCN);
        attrs.put(X509Principal.O, "www.jxta.org");

        // XXX bondolo 20040405 wouldn't SN or UID be a better choice?
        // set ou to 20 random digits
        byte[] ou = new byte[10];

        UTILS.srng.nextBytes(ou);
        String ouStr = toHexDigits(ou);

        attrs.put(X509Principal.OU, ouStr);

        X509Principal subject = new X509Principal(attrs);
        X500Principal samesubject = new X500Principal(subject.getEncoded());
        KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");

        g.initialize(1024, UTILS.srng);

        KeyPair keypair = g.generateKeyPair();

        return genCert(samesubject, keypair, issuerinfo);

    } catch (NoSuchAlgorithmException e) {

        Logging.logCheckedSevere(LOG, "Could not generate certificate\n\n", e);

        SecurityException failure = new SecurityException("Could not generate certificate");
        failure.initCause(e);
        throw failure;

    }
}

From source file:org.glite.voms.PKIUtils.java

License:Open Source License

/**
 * Gets the MD5 hash value of the given principal.
 *
 * @param principal the principal.//from   www . jav a  2s  .c  o m
 *
 * @return the hash value.
 *
 * @throws IllegalArgumentException if crl is null.
 * @throws InvalidStateException if the MD5 algorithm is not supported.
 */
public static String getHash(X509Principal principal) {
    if (principal != null) {
        byte[] array = principal.getEncoded();
        return getHash(array);
    }
    throw new IllegalArgumentException("Null name passed to getHash()");
}

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();

    /*/*from   www  .j av  a2s  .  c  om*/
      "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());
}