Search in sources :

Example 41 with ASN1BitString

use of com.unboundid.asn1.ASN1BitString in project ldapsdk by pingidentity.

the class X509Certificate method generateSelfSignedCertificate.

/**
 * Generates a self-signed X.509 certificate with the provided information.
 *
 * @param  signatureAlgorithm  The algorithm to use to generate the signature.
 *                             This must not be {@code null}.
 * @param  keyPair             The key pair for the certificate.  This must
 *                             not be {@code null}.
 * @param  subjectDN           The subject DN for the certificate.  This must
 *                             not be {@code null}.
 * @param  notBefore           The validity start time for the certificate.
 * @param  notAfter            The validity end time for the certificate.
 * @param  extensions          The set of extensions to include in the
 *                             certificate.  This may be {@code null} or empty
 *                             if the certificate should not include any
 *                             custom extensions.  Note that the generated
 *                             certificate will automatically include a
 *                             {@link SubjectKeyIdentifierExtension}, so that
 *                             should not be provided.
 *
 * @return  An {@code ObjectPair} that contains both the self-signed
 *          certificate and its corresponding key pair.
 *
 * @throws  CertException  If a problem is encountered while creating the
 *                         certificate.
 */
@NotNull()
public static X509Certificate generateSelfSignedCertificate(@NotNull final SignatureAlgorithmIdentifier signatureAlgorithm, @NotNull final KeyPair keyPair, @NotNull final DN subjectDN, final long notBefore, final long notAfter, @Nullable final X509CertificateExtension... extensions) throws CertException {
    // Extract the parameters and encoded public key from the generated key
    // pair.  And while we're at it, generate a subject key identifier from
    // the encoded public key.
    DecodedPublicKey decodedPublicKey = null;
    final ASN1BitString encodedPublicKey;
    final ASN1Element publicKeyAlgorithmParameters;
    final byte[] subjectKeyIdentifier;
    final OID publicKeyAlgorithmOID;
    try {
        final ASN1Element[] pkElements = ASN1Sequence.decodeAsSequence(keyPair.getPublic().getEncoded()).elements();
        final ASN1Element[] pkAlgIDElements = ASN1Sequence.decodeAsSequence(pkElements[0]).elements();
        publicKeyAlgorithmOID = pkAlgIDElements[0].decodeAsObjectIdentifier().getOID();
        if (pkAlgIDElements.length == 1) {
            publicKeyAlgorithmParameters = null;
        } else {
            publicKeyAlgorithmParameters = pkAlgIDElements[1];
        }
        encodedPublicKey = pkElements[1].decodeAsBitString();
        try {
            if (publicKeyAlgorithmOID.equals(PublicKeyAlgorithmIdentifier.RSA.getOID())) {
                decodedPublicKey = new RSAPublicKey(encodedPublicKey);
            } else if (publicKeyAlgorithmOID.equals(PublicKeyAlgorithmIdentifier.EC.getOID())) {
                decodedPublicKey = new EllipticCurvePublicKey(encodedPublicKey);
            }
        } catch (final Exception e) {
            Debug.debugException(e);
        }
        final MessageDigest sha256 = CryptoHelper.getMessageDigest(SubjectKeyIdentifierExtension.SUBJECT_KEY_IDENTIFIER_DIGEST_ALGORITHM);
        subjectKeyIdentifier = sha256.digest(encodedPublicKey.getBytes());
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new CertException(ERR_CERT_GEN_SELF_SIGNED_CANNOT_PARSE_KEY_PAIR.get(StaticUtils.getExceptionMessage(e)), e);
    }
    // Construct the set of all extensions for the certificate.
    final ArrayList<X509CertificateExtension> extensionList = new ArrayList<>(10);
    extensionList.add(new SubjectKeyIdentifierExtension(false, new ASN1OctetString(subjectKeyIdentifier)));
    if (extensions != null) {
        for (final X509CertificateExtension e : extensions) {
            if (!e.getOID().equals(SubjectKeyIdentifierExtension.SUBJECT_KEY_IDENTIFIER_OID)) {
                extensionList.add(e);
            }
        }
    }
    final X509CertificateExtension[] allExtensions = new X509CertificateExtension[extensionList.size()];
    extensionList.toArray(allExtensions);
    // Encode the tbsCertificate sequence for the certificate and use it to
    // generate the certificate's signature.
    final BigInteger serialNumber = generateSerialNumber();
    final ASN1BitString encodedSignature = generateSignature(signatureAlgorithm, keyPair.getPrivate(), serialNumber, subjectDN, notBefore, notAfter, subjectDN, publicKeyAlgorithmOID, publicKeyAlgorithmParameters, encodedPublicKey, allExtensions);
    // Construct and return the signed certificate and the private key.
    return new X509Certificate(X509CertificateVersion.V3, serialNumber, signatureAlgorithm.getOID(), null, encodedSignature, subjectDN, notBefore, notAfter, subjectDN, publicKeyAlgorithmOID, publicKeyAlgorithmParameters, encodedPublicKey, decodedPublicKey, null, null, allExtensions);
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ArrayList(java.util.ArrayList) OID(com.unboundid.util.OID) ASN1BitString(com.unboundid.asn1.ASN1BitString) ASN1Exception(com.unboundid.asn1.ASN1Exception) CertificateException(java.security.cert.CertificateException) ASN1Element(com.unboundid.asn1.ASN1Element) BigInteger(java.math.BigInteger) ASN1BigInteger(com.unboundid.asn1.ASN1BigInteger) MessageDigest(java.security.MessageDigest) NotNull(com.unboundid.util.NotNull)

Example 42 with ASN1BitString

use of com.unboundid.asn1.ASN1BitString in project ldapsdk by pingidentity.

the class X509Certificate method generateIssuerSignedCertificate.

/**
 * Generates an issuer-signed X.509 certificate with the provided information.
 *
 * @param  signatureAlgorithm
 *              The algorithm to use to generate the signature.  This must not
 *              be {@code null}.
 * @param  issuerCertificate
 *              The certificate for the issuer.  This must not be
 *              {@code null}.
 * @param  issuerPrivateKey
 *              The private key for the issuer.  This  must not be
 *              {@code null}.
 * @param  publicKeyAlgorithmOID
 *              The OID for the certificate's public key algorithm.  This must
 *              not be {@code null}.
 * @param  publicKeyAlgorithmParameters
 *              The encoded public key algorithm parameters for the
 *              certificate.  This may be {@code null} if there are no
 *              parameters.
 * @param  encodedPublicKey
 *              The encoded public key for the certificate.  This must not be
 *              {@code null}.
 * @param  decodedPublicKey
 *              The decoded public key for the certificate.  This may be
 *              {@code null} if it is not available.
 * @param  subjectDN
 *              The subject DN for the certificate.  This must not be
 *              {@code null}.
 * @param  notBefore
 *              The validity start time for the certificate.
 * @param  notAfter
 *              The validity end time for the certificate.
 * @param  extensions
 *              The set of extensions to include in the certificate.  This
 *              may be {@code null} or empty if the certificate should not
 *              include any custom extensions.  Note that the generated
 *              certificate will automatically include a
 *              {@link SubjectKeyIdentifierExtension}, so that should not be
 *              provided.  In addition, if the issuer certificate includes its
 *              own {@code SubjectKeyIdentifierExtension}, then its value will
 *              be used to generate an
 *              {@link AuthorityKeyIdentifierExtension}.
 *
 * @return  The issuer-signed certificate.
 *
 * @throws  CertException  If a problem is encountered while creating the
 *                         certificate.
 */
@NotNull()
public static X509Certificate generateIssuerSignedCertificate(@NotNull final SignatureAlgorithmIdentifier signatureAlgorithm, @NotNull final X509Certificate issuerCertificate, @NotNull final PrivateKey issuerPrivateKey, @NotNull final OID publicKeyAlgorithmOID, @Nullable final ASN1Element publicKeyAlgorithmParameters, @NotNull final ASN1BitString encodedPublicKey, @Nullable final DecodedPublicKey decodedPublicKey, @NotNull final DN subjectDN, final long notBefore, final long notAfter, @NotNull final X509CertificateExtension... extensions) throws CertException {
    // Generate a subject key identifier from the encoded public key.
    final byte[] subjectKeyIdentifier;
    try {
        final MessageDigest sha256 = CryptoHelper.getMessageDigest(SubjectKeyIdentifierExtension.SUBJECT_KEY_IDENTIFIER_DIGEST_ALGORITHM);
        subjectKeyIdentifier = sha256.digest(encodedPublicKey.getBytes());
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new CertException(ERR_CERT_GEN_ISSUER_SIGNED_CANNOT_GENERATE_KEY_ID.get(StaticUtils.getExceptionMessage(e)), e);
    }
    // If the issuer certificate contains a subject key identifier, then
    // extract it to use as the authority key identifier.
    ASN1OctetString authorityKeyIdentifier = null;
    for (final X509CertificateExtension e : issuerCertificate.extensions) {
        if (e instanceof SubjectKeyIdentifierExtension) {
            authorityKeyIdentifier = ((SubjectKeyIdentifierExtension) e).getKeyIdentifier();
        }
    }
    // Construct the set of all extensions for the certificate.
    final ArrayList<X509CertificateExtension> extensionList = new ArrayList<>(10);
    extensionList.add(new SubjectKeyIdentifierExtension(false, new ASN1OctetString(subjectKeyIdentifier)));
    if (authorityKeyIdentifier == null) {
        extensionList.add(new AuthorityKeyIdentifierExtension(false, null, new GeneralNamesBuilder().addDirectoryName(issuerCertificate.subjectDN).build(), issuerCertificate.serialNumber));
    } else {
        extensionList.add(new AuthorityKeyIdentifierExtension(false, authorityKeyIdentifier, null, null));
    }
    if (extensions != null) {
        for (final X509CertificateExtension e : extensions) {
            if (e.getOID().equals(SubjectKeyIdentifierExtension.SUBJECT_KEY_IDENTIFIER_OID) || e.getOID().equals(AuthorityKeyIdentifierExtension.AUTHORITY_KEY_IDENTIFIER_OID)) {
                continue;
            }
            extensionList.add(e);
        }
    }
    final X509CertificateExtension[] allExtensions = new X509CertificateExtension[extensionList.size()];
    extensionList.toArray(allExtensions);
    // Encode the tbsCertificate sequence for the certificate and use it to
    // generate the certificate's signature.
    final BigInteger serialNumber = generateSerialNumber();
    final ASN1BitString encodedSignature = generateSignature(signatureAlgorithm, issuerPrivateKey, serialNumber, issuerCertificate.subjectDN, notBefore, notAfter, subjectDN, publicKeyAlgorithmOID, publicKeyAlgorithmParameters, encodedPublicKey, allExtensions);
    // Construct and return the signed certificate.
    return new X509Certificate(X509CertificateVersion.V3, serialNumber, signatureAlgorithm.getOID(), null, encodedSignature, issuerCertificate.subjectDN, notBefore, notAfter, subjectDN, publicKeyAlgorithmOID, publicKeyAlgorithmParameters, encodedPublicKey, decodedPublicKey, null, null, allExtensions);
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ArrayList(java.util.ArrayList) ASN1Exception(com.unboundid.asn1.ASN1Exception) CertificateException(java.security.cert.CertificateException) ASN1BitString(com.unboundid.asn1.ASN1BitString) BigInteger(java.math.BigInteger) ASN1BigInteger(com.unboundid.asn1.ASN1BigInteger) MessageDigest(java.security.MessageDigest) NotNull(com.unboundid.util.NotNull)

Example 43 with ASN1BitString

use of com.unboundid.asn1.ASN1BitString in project ldapsdk by pingidentity.

the class X509Certificate method generateSignature.

/**
 * Generates a signature for the certificate with the provided information.
 *
 * @param  signatureAlgorithm            The signature algorithm to use to
 *                                       generate the signature.  This must
 *                                       not be {@code null}.
 * @param  privateKey                    The private key to use to sign the
 *                                       certificate.  This must not be
 *                                       {@code null}.
 * @param  serialNumber                  The serial number for the
 *                                       certificate.  This must not be
 *                                       {@code null}.
 * @param  issuerDN                      The issuer DN for the certificate.
 *                                       This must not be {@code null}.
 * @param  notBefore                     The validity start time for the
 *                                       certificate.
 * @param  notAfter                      The validity end time for the
 *                                       certificate.
 * @param  subjectDN                     The subject DN for the certificate.
 *                                       This must not be {@code null}.
 * @param  publicKeyAlgorithmOID         The OID for the public key algorithm.
 *                                       This must not be {@code null}.
 * @param  publicKeyAlgorithmParameters  The encoded public key algorithm
 *                                       parameters.  This may be
 *                                       {@code null} if no parameters are
 *                                       needed.
 * @param  encodedPublicKey              The encoded representation of the
 *                                       public key.  This must not be
 *                                       {@code null}.
 * @param  extensions                    The set of extensions to include in
 *                                       the certificate.  This must not be
 *                                       {@code null} but may be empty.
 *
 * @return  An encoded representation of the generated signature.
 *
 * @throws  CertException  If a problem is encountered while generating the
 *                         certificate.
 */
@NotNull()
private static ASN1BitString generateSignature(@NotNull final SignatureAlgorithmIdentifier signatureAlgorithm, @NotNull final PrivateKey privateKey, @NotNull final BigInteger serialNumber, @NotNull final DN issuerDN, final long notBefore, final long notAfter, @NotNull final DN subjectDN, @NotNull final OID publicKeyAlgorithmOID, @Nullable final ASN1Element publicKeyAlgorithmParameters, @NotNull final ASN1BitString encodedPublicKey, @NotNull final X509CertificateExtension... extensions) throws CertException {
    // Get and initialize the signature generator.
    final Signature signature;
    try {
        signature = CryptoHelper.getSignature(signatureAlgorithm.getJavaName());
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new CertException(ERR_CERT_GEN_SIGNATURE_CANNOT_GET_SIGNATURE_GENERATOR.get(signatureAlgorithm.getJavaName(), StaticUtils.getExceptionMessage(e)), e);
    }
    try {
        signature.initSign(privateKey);
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new CertException(ERR_CERT_GEN_SIGNATURE_CANNOT_INIT_SIGNATURE_GENERATOR.get(signatureAlgorithm.getJavaName(), StaticUtils.getExceptionMessage(e)), e);
    }
    // signature.
    try {
        final ArrayList<ASN1Element> tbsCertificateElements = new ArrayList<>(8);
        tbsCertificateElements.add(new ASN1Element(TYPE_EXPLICIT_VERSION, new ASN1Integer(X509CertificateVersion.V3.getIntValue()).encode()));
        tbsCertificateElements.add(new ASN1BigInteger(serialNumber));
        tbsCertificateElements.add(new ASN1Sequence(new ASN1ObjectIdentifier(signatureAlgorithm.getOID())));
        tbsCertificateElements.add(encodeName(issuerDN));
        tbsCertificateElements.add(encodeValiditySequence(notBefore, notAfter));
        tbsCertificateElements.add(encodeName(subjectDN));
        if (publicKeyAlgorithmParameters == null) {
            tbsCertificateElements.add(new ASN1Sequence(new ASN1Sequence(new ASN1ObjectIdentifier(publicKeyAlgorithmOID)), encodedPublicKey));
        } else {
            tbsCertificateElements.add(new ASN1Sequence(new ASN1Sequence(new ASN1ObjectIdentifier(publicKeyAlgorithmOID), publicKeyAlgorithmParameters), encodedPublicKey));
        }
        final ArrayList<ASN1Element> extensionElements = new ArrayList<>(extensions.length);
        for (final X509CertificateExtension e : extensions) {
            extensionElements.add(e.encode());
        }
        tbsCertificateElements.add(new ASN1Element(TYPE_EXPLICIT_EXTENSIONS, new ASN1Sequence(extensionElements).encode()));
        final byte[] tbsCertificateBytes = new ASN1Sequence(tbsCertificateElements).encode();
        signature.update(tbsCertificateBytes);
        final byte[] signatureBytes = signature.sign();
        return new ASN1BitString(ASN1BitString.getBitsForBytes(signatureBytes));
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new CertException(ERR_CERT_GEN_SIGNATURE_CANNOT_COMPUTE.get(signatureAlgorithm.getJavaName(), StaticUtils.getExceptionMessage(e)), e);
    }
}
Also used : ArrayList(java.util.ArrayList) ASN1BigInteger(com.unboundid.asn1.ASN1BigInteger) ASN1Integer(com.unboundid.asn1.ASN1Integer) ASN1Exception(com.unboundid.asn1.ASN1Exception) CertificateException(java.security.cert.CertificateException) ASN1BitString(com.unboundid.asn1.ASN1BitString) ASN1Sequence(com.unboundid.asn1.ASN1Sequence) Signature(java.security.Signature) ASN1Element(com.unboundid.asn1.ASN1Element) ASN1ObjectIdentifier(com.unboundid.asn1.ASN1ObjectIdentifier) NotNull(com.unboundid.util.NotNull)

Example 44 with ASN1BitString

use of com.unboundid.asn1.ASN1BitString in project ldapsdk by pingidentity.

the class RSAPublicKey method encode.

/**
 * Encodes this RSA public key.
 *
 * @return  The encoded representation of this RSA public key.
 */
@NotNull()
ASN1BitString encode() {
    final ASN1Sequence publicKeySequence = new ASN1Sequence(new ASN1BigInteger(modulus), new ASN1BigInteger(publicExponent));
    final boolean[] bits = ASN1BitString.getBitsForBytes(publicKeySequence.encode());
    return new ASN1BitString(bits);
}
Also used : ASN1Sequence(com.unboundid.asn1.ASN1Sequence) ASN1BigInteger(com.unboundid.asn1.ASN1BigInteger) ASN1BitString(com.unboundid.asn1.ASN1BitString) NotNull(com.unboundid.util.NotNull)

Example 45 with ASN1BitString

use of com.unboundid.asn1.ASN1BitString in project attestation by TokenScript.

the class ASN1Util method restorePublicKey.

/**
 * Extract the public key from its DER encoded BITString
 * @param input
 * @return
 */
public static AsymmetricKeyParameter restorePublicKey(byte[] input, X9ECParameters parameters, String oid) throws IOException {
    AlgorithmIdentifier identifierEnc = new AlgorithmIdentifier(new ASN1ObjectIdentifier(oid), parameters.toASN1Primitive());
    ASN1BitString keyEnc = DERBitString.getInstance(input);
    ASN1Sequence spkiEnc = new DERSequence(new ASN1Encodable[] { identifierEnc, keyEnc });
    SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(spkiEnc);
    return PublicKeyFactory.createKey(spki);
}
Also used : ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DERSequence(org.bouncycastle.asn1.DERSequence) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) ASN1BitString(org.bouncycastle.asn1.ASN1BitString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Aggregations

ASN1BitString (com.unboundid.asn1.ASN1BitString)72 Test (org.testng.annotations.Test)62 DN (com.unboundid.ldap.sdk.DN)49 ASN1Null (com.unboundid.asn1.ASN1Null)36 OID (com.unboundid.util.OID)33 ASN1ObjectIdentifier (com.unboundid.asn1.ASN1ObjectIdentifier)26 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)25 ASN1Sequence (com.unboundid.asn1.ASN1Sequence)24 ASN1Element (com.unboundid.asn1.ASN1Element)23 ASN1BigInteger (com.unboundid.asn1.ASN1BigInteger)22 ASN1Integer (com.unboundid.asn1.ASN1Integer)20 IOException (java.io.IOException)16 ASN1BitString (com.github.zhenwei.core.asn1.ASN1BitString)14 ASN1BitString (org.bouncycastle.asn1.ASN1BitString)11 BigInteger (java.math.BigInteger)10 ArrayList (java.util.ArrayList)10 ASN1GeneralizedTime (com.unboundid.asn1.ASN1GeneralizedTime)9 NotNull (com.unboundid.util.NotNull)9 Date (java.util.Date)8 KeyPair (java.security.KeyPair)7