Example usage for java.security.cert X509Certificate getTBSCertificate

List of usage examples for java.security.cert X509Certificate getTBSCertificate

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getTBSCertificate.

Prototype

public abstract byte[] getTBSCertificate() throws CertificateEncodingException;

Source Link

Document

Gets the DER-encoded certificate information, the tbsCertificate from this certificate.

Usage

From source file:CertificateSigner.java

public static void main(String[] args) {
    String ksname = null; // the keystore name
    String alias = null; // the private key alias
    String inname = null; // the input file name
    String outname = null; // the output file name
    for (int i = 0; i < args.length; i += 2) {
        if (args[i].equals("-keystore"))
            ksname = args[i + 1];/*w  w  w.j a v a 2  s  .  c o m*/
        else if (args[i].equals("-alias"))
            alias = args[i + 1];
        else if (args[i].equals("-infile"))
            inname = args[i + 1];
        else if (args[i].equals("-outfile"))
            outname = args[i + 1];
        else
            usage();
    }

    if (ksname == null || alias == null || inname == null || outname == null)
        usage();

    try {
        Console console = System.console();
        if (console == null)
            error("No console");
        char[] password = console.readPassword("Keystore password: ");
        KeyStore store = KeyStore.getInstance("JKS", "SUN");
        InputStream in = new FileInputStream(ksname);
        store.load(in, password);
        Arrays.fill(password, ' ');
        in.close();

        char[] keyPassword = console.readPassword("Key password for %s: ", alias);
        PrivateKey issuerPrivateKey = (PrivateKey) store.getKey(alias, keyPassword);
        Arrays.fill(keyPassword, ' ');

        if (issuerPrivateKey == null)
            error("No such private key");

        in = new FileInputStream(inname);

        CertificateFactory factory = CertificateFactory.getInstance("X.509");

        X509Certificate inCert = (X509Certificate) factory.generateCertificate(in);
        in.close();
        byte[] inCertBytes = inCert.getTBSCertificate();

        X509Certificate issuerCert = (X509Certificate) store.getCertificate(alias);
        Principal issuer = issuerCert.getSubjectDN();
        String issuerSigAlg = issuerCert.getSigAlgName();

        FileOutputStream out = new FileOutputStream(outname);

        X509CertInfo info = new X509CertInfo(inCertBytes);
        info.set(X509CertInfo.ISSUER, new CertificateIssuerName((X500Name) issuer));

        X509CertImpl outCert = new X509CertImpl(info);
        outCert.sign(issuerPrivateKey, issuerSigAlg);
        outCert.derEncode(out);

        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.ripe.rpki.commons.crypto.x509cert.X509CertificateUtil.java

/**
 * Get a base 64-encoded, DER-encoded X.509 subjectPublicKeyInfo as used for the Trust Anchor Locator (TAL)
 *
 * @throws X509CertificateOperationException
 *
 * @throws IOException/*from   ww  w.  j  ava2s .c om*/
 */
public static String getEncodedSubjectPublicKeyInfo(X509Certificate certificate) {

    byte[] tbsCertificate;
    try {
        tbsCertificate = certificate.getTBSCertificate();
    } catch (CertificateEncodingException e) {
        throw new X509CertificateOperationException("Can't extract TBSCertificate from certificate", e);
    }
    ASN1Sequence tbsCertificateSequence = (ASN1Sequence) Asn1Util.decode(tbsCertificate);
    TBSCertificateStructure tbsCertificateStructure = new TBSCertificateStructure(tbsCertificateSequence);
    SubjectPublicKeyInfo subjectPublicKeyInfo = tbsCertificateStructure.getSubjectPublicKeyInfo();

    try {
        byte[] data = subjectPublicKeyInfo.getEncoded();
        Base64Encoder encoder = new Base64Encoder();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        encoder.encode(data, 0, data.length, out);
        out.flush();
        return out.toString();
    } catch (IOException e) {
        throw new X509CertificateOperationException("Can't encode SubjectPublicKeyInfo for certificate", e);
    }
}

From source file:com.archivas.clienttools.arcutils.utils.net.SSLCertChain.java

public String getMD5FingerprintString() {
    X509Certificate cert = getCertificateList().get(0);
    String s = null;/*from   ww  w  .  j a v  a2s. c om*/
    try {
        s = byteArrayToColonSeparatedHexString(DigestUtils.md5(cert.getTBSCertificate()), ":");
    } catch (CertificateEncodingException e) {
        LOG.log(Level.WARNING, "Error generating MD5 Fingerprint for SSL Certificate : " + toString());
    }
    return s;
}

From source file:com.archivas.clienttools.arcutils.utils.net.SSLCertChain.java

public String getShaFingerprintString() {
    X509Certificate cert = getCertificateList().get(0);
    String s = null;/* w  ww .  ja v a2s  .c  o m*/
    try {
        s = byteArrayToColonSeparatedHexString(DigestUtils.sha(cert.getTBSCertificate()), ":");
    } catch (CertificateEncodingException e) {
        LOG.log(Level.WARNING, "Error generating MD5 Fingerprint for SSL Certificate : " + toString());
    }
    return s;
}

From source file:it.cnr.icar.eric.server.security.authentication.CertificateAuthority.java

/**
 * Signed specified cert using the private key of RegistryOperator.
 * Warning this uses Sun's JDK impl specific classes and will not work
 * with other JDK impls.// www. j a  v a2s  .  c  o m
 *
 */
@SuppressWarnings("static-access")
X509Certificate signCertificate(X509Certificate inCert) throws RegistryException {
    X509CertImpl signedCert = null;

    try {
        X509CertImpl caCert = (X509CertImpl) getCACertificate();
        X509CertInfo caCertInfo = new X509CertInfo(caCert.getTBSCertificate());
        X509CertInfo inCertInfo = new X509CertInfo(inCert.getTBSCertificate());

        // Use catch (certs subject name as signed cert's issuer name
        CertificateSubjectName caCertSubjectName = (CertificateSubjectName) caCertInfo
                .get(X509CertInfo.SUBJECT);
        CertificateIssuerName signedCertIssuerName = new CertificateIssuerName(
                (X500Name) caCertSubjectName.get(CertificateSubjectName.DN_NAME));

        inCertInfo.set(X509CertInfo.ISSUER, signedCertIssuerName);
        signedCert = new X509CertImpl(inCertInfo);

        //TODO: Need to remove hardcoding below and instead somehow use info.algId => algName
        //            signedCert.sign(ac.getPrivateKey(ac.ALIAS_REGISTRY_OPERATOR, ac.ALIAS_REGISTRY_OPERATOR), "MD5WithRSA"); // JDK6
        //            signedCert.sign(ac.getPrivateKey(ac.ALIAS_REGISTRY_OPERATOR, ac.ALIAS_REGISTRY_OPERATOR), "SHA256withRSA"); // JDK7

        // removed hardcoding
        signedCert.sign(ac.getPrivateKey(ac.ALIAS_REGISTRY_OPERATOR, ac.ALIAS_REGISTRY_OPERATOR),
                inCert.getSigAlgName());

    } catch (java.security.GeneralSecurityException e) {
        throw new RegistryException(
                ServerResourceBundle.getInstance().getString("message.ErrorSigningRegIssuedCert"), e);
    } catch (java.io.IOException e) {
        throw new RegistryException(
                ServerResourceBundle.getInstance().getString("message.ErrorSigningRegIssuedCert"), e);
    }

    return signedCert;
}

From source file:org.apache.pdfbox.pdmodel.encryption.PublicKeySecurityHandler.java

private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
        throws GeneralSecurityException, IOException {
    ASN1InputStream asn1inputstream = new ASN1InputStream(
            new ByteArrayInputStream(x509certificate.getTBSCertificate()));
    TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure
            .getInstance(asn1inputstream.readObject());
    AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo()
            .getAlgorithmId();// w w  w  .  j a  va 2  s .  c om
    IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbscertificatestructure.getIssuer(),
            tbscertificatestructure.getSerialNumber().getValue());
    Cipher cipher = Cipher.getInstance(algorithmidentifier.getObjectId().getId());
    cipher.init(1, x509certificate.getPublicKey());
    DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
    RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
    return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring);
}

From source file:org.globus.gsi.util.CertificateUtil.java

/**
 * Extracts the TBS certificate from the given certificate.
 *
 * @param cert the X.509 certificate to extract the TBS certificate from.
 * @return the TBS certificate//from   w  w  w.  ja  v  a 2  s . c o m
 * @throws IOException                  if extraction fails.
 * @throws CertificateEncodingException if extraction fails.
 */
public static TBSCertificateStructure getTBSCertificateStructure(X509Certificate cert)
        throws CertificateEncodingException, IOException {
    ASN1Primitive obj = toASN1Primitive(cert.getTBSCertificate());
    return TBSCertificateStructure.getInstance(obj);
}

From source file:org.globus.pkcs11.PKCS11Util.java

/**
 * Creates a signed certificate from the passed in certificate.  Signs the 
 * certificate with the specified private key
 *
 **///from   w w w .j a  va  2  s  . co m
public static X509Certificate signCertificate(X509Certificate cert, PKCS11Object userPrivKeyHandle)
        throws PKCS11Exception {
    try {
        signInit(userPrivKeyHandle);
        logger.debug("Signing a certificate");
        cert.setSignatureAlgorithm(AlgorithmID.md5WithRSAEncryption);
        byte[] certBytes = cert.getTBSCertificate();

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(certBytes);
        byte[] hashBytes = md5.digest();

        byte[] signature = new byte[300];
        int sigLength;
        byte[] revSignature;

        ASN1Object digestInfo = new SEQUENCE();
        digestInfo.addComponent(AlgorithmID.md5.toASN1Object());
        digestInfo.addComponent(new OCTET_STRING(hashBytes));
        byte[] toBeEncrypted = DerCoder.encode(digestInfo);

        sigLength = session.sign(toBeEncrypted, 0, toBeEncrypted.length, signature, 0);
        revSignature = new byte[sigLength];
        System.arraycopy(signature, 0, revSignature, 0, sigLength);

        ASN1Object tbsCert = DerCoder.decode(certBytes);

        SEQUENCE certASN1 = new SEQUENCE();
        certASN1.addComponent(tbsCert);
        certASN1.addComponent(AlgorithmID.md5WithRSAEncryption.toASN1Object());
        certASN1.addComponent(new BIT_STRING(revSignature));

        return new X509Certificate(DerCoder.encode(certASN1));
    } catch (Exception e) {
        throw new PKCS11Exception("Failed to sign proxy certificate", e);
    }
}

From source file:org.jboss.as.test.integration.security.common.CoreUtils.java

private static void createTemporaryCertFile(X509Certificate cert, File outputFile) throws Exception {
    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        fos.write(cert.getTBSCertificate());
    }/*from w  w  w. j  a  v a 2s.  co  m*/
}