Search in sources :

Example 36 with ASN1BitString

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

the class X509CertificateTestCase method testCertificateWithInvalidRSAPublicKey.

/**
 * Tests a valid X.509 certificate that claims to have an RSA public key, but
 * whose public key cannot actually be parsed as an RSA key.  This won't
 * cause an error, but will result in the public key not being available.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test()
public void testCertificateWithInvalidRSAPublicKey() throws Exception {
    final long notBefore = System.currentTimeMillis();
    final long notAfter = notBefore + (365L * 24L * 60L * 60L * 1000L);
    X509Certificate c = new X509Certificate(X509CertificateVersion.V1, BigInteger.valueOf(123456789L), new OID("1.2.3.4"), new ASN1Null(), new ASN1BitString(new boolean[1235]), new DN("CN=Issuer,O=Example Corp,C=US"), notBefore, notAfter, new DN("CN=ldap.example.com,O=Example Corp,C=US"), PublicKeyAlgorithmIdentifier.RSA.getOID(), new ASN1Null(), new ASN1BitString(new boolean[123]), null, null, null);
    assertNotNull(c.getX509CertificateBytes());
    c = new X509Certificate(c.encode().encode());
    assertNotNull(c.getVersion());
    assertEquals(c.getVersion(), X509CertificateVersion.V1);
    assertNotNull(c.getSerialNumber());
    assertEquals(c.getSerialNumber(), BigInteger.valueOf(123456789L));
    assertNotNull(c.getSignatureAlgorithmOID());
    assertEquals(c.getSignatureAlgorithmOID(), new OID("1.2.3.4"));
    assertNull(c.getSignatureAlgorithmName());
    assertNotNull(c.getSignatureAlgorithmNameOrOID());
    assertEquals(c.getSignatureAlgorithmNameOrOID(), "1.2.3.4");
    assertNotNull(c.getSignatureAlgorithmParameters());
    assertNotNull(c.getIssuerDN());
    assertEquals(c.getIssuerDN(), new DN("CN=Issuer,O=Example Corp,C=US"));
    // NOTE:  For some moronic reasons, certificates tend to use UTCTime instead
    // of generalized time when encoding notBefore and notAfter values, despite
    // the spec allowing either one, and despite UTCTime only supporting a
    // two-digit year and no sub-second component.  So we can't check for
    // exact equivalence  of the notBefore and notAfter values.  Instead, just
    // make sure that the values are within 2000 milliseconds of the expected
    // value.
    assertTrue(Math.abs(c.getNotBeforeTime() - notBefore) < 2000L);
    assertNotNull(c.getNotBeforeDate());
    assertEquals(c.getNotBeforeDate(), new Date(c.getNotBeforeTime()));
    assertTrue(Math.abs(c.getNotAfterTime() - notAfter) < 2000L);
    assertNotNull(c.getNotAfterDate());
    assertEquals(c.getNotAfterDate(), new Date(c.getNotAfterTime()));
    assertNotNull(c.getSubjectDN());
    assertEquals(c.getSubjectDN(), new DN("CN=ldap.example.com,O=Example Corp,C=US"));
    assertNotNull(c.getPublicKeyAlgorithmOID());
    assertEquals(c.getPublicKeyAlgorithmOID(), PublicKeyAlgorithmIdentifier.RSA.getOID());
    assertNotNull(c.getPublicKeyAlgorithmName());
    assertEquals(c.getPublicKeyAlgorithmName(), "RSA");
    assertNotNull(c.getPublicKeyAlgorithmNameOrOID());
    assertEquals(c.getPublicKeyAlgorithmNameOrOID(), "RSA");
    assertNotNull(c.getPublicKeyAlgorithmParameters());
    assertNotNull(c.getEncodedPublicKey());
    assertNull(c.getDecodedPublicKey());
    assertNull(c.getIssuerUniqueID());
    assertNull(c.getSubjectUniqueID());
    assertNotNull(c.getExtensions());
    assertTrue(c.getExtensions().isEmpty());
    assertNotNull(c.getSignatureValue());
    assertNotNull(c.toString());
    assertNotNull(c.toPEM());
    assertFalse(c.toPEM().isEmpty());
    assertNotNull(c.toPEMString());
    assertNotNull(c.getX509CertificateBytes());
    assertNotNull(c.getSHA1Fingerprint());
    assertNotNull(c.getSHA256Fingerprint());
}
Also used : DN(com.unboundid.ldap.sdk.DN) OID(com.unboundid.util.OID) ASN1BitString(com.unboundid.asn1.ASN1BitString) Date(java.util.Date) ASN1Null(com.unboundid.asn1.ASN1Null) Test(org.testng.annotations.Test)

Example 37 with ASN1BitString

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

the class X509CertificateTestCase method testDecodeSignatureAlgorithmElementNotSequence.

/**
 * Tests the behavior when trying to decode a certificate with a signature
 * algorithm element that is not a valid sequence.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test(expectedExceptions = { CertException.class })
public void testDecodeSignatureAlgorithmElementNotSequence() throws Exception {
    final long notBefore = System.currentTimeMillis();
    final long notAfter = notBefore + (365L * 24L * 60L * 60L * 1000L);
    final ASN1Sequence valueSequence = new ASN1Sequence(new ASN1Sequence(new ASN1Element((byte) 0xA0, new ASN1Integer(2).encode()), new ASN1BigInteger(12435L), new ASN1OctetString("not a valid sequence"), X509Certificate.encodeName(new DN("CN=issuer")), new ASN1Sequence(new ASN1UTCTime(notBefore), new ASN1UTCTime(notAfter)), X509Certificate.encodeName(new DN("CN=ldap.example.com")), new ASN1Sequence(new ASN1Sequence(new ASN1ObjectIdentifier(new OID("1.2.3.5")), new ASN1Null()), new ASN1BitString(new boolean[1024]))), new ASN1Sequence(new ASN1ObjectIdentifier(new OID("1.2.3.4")), new ASN1Null()), new ASN1BitString(new boolean[1024]));
    new X509Certificate(valueSequence.encode());
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ASN1UTCTime(com.unboundid.asn1.ASN1UTCTime) ASN1BigInteger(com.unboundid.asn1.ASN1BigInteger) DN(com.unboundid.ldap.sdk.DN) ASN1Integer(com.unboundid.asn1.ASN1Integer) OID(com.unboundid.util.OID) ASN1BitString(com.unboundid.asn1.ASN1BitString) ASN1Sequence(com.unboundid.asn1.ASN1Sequence) ASN1Element(com.unboundid.asn1.ASN1Element) ASN1ObjectIdentifier(com.unboundid.asn1.ASN1ObjectIdentifier) ASN1Null(com.unboundid.asn1.ASN1Null) Test(org.testng.annotations.Test)

Example 38 with ASN1BitString

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

the class X509CertificateTestCase method testVerifySignatureUnrecognizedSignatureAlgorithm.

/**
 * Tests the behavior of the {@code verifySignature} method with an
 * unrecognized signature algorithm.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test(expectedExceptions = { CertException.class })
public void testVerifySignatureUnrecognizedSignatureAlgorithm() throws Exception {
    final ObjectPair<X509Certificate, KeyPair> p = X509Certificate.generateSelfSignedCertificate(SignatureAlgorithmIdentifier.SHA_256_WITH_RSA, PublicKeyAlgorithmIdentifier.RSA, 2048, new DN("CN=ldap.example.com,O=Example Corporation,C=US"), System.currentTimeMillis(), System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365L), new SubjectAlternativeNameExtension(false, new GeneralNamesBuilder().addDNSName("ldap.example.com").build()));
    final X509Certificate c = p.getFirst();
    final X509CertificateExtension[] extensions = new X509CertificateExtension[c.getExtensions().size()];
    c.getExtensions().toArray(extensions);
    final X509Certificate cert = new X509Certificate(c.getVersion(), c.getSerialNumber(), new OID("1.2.3.4.5.6.7.8"), c.getSignatureAlgorithmParameters(), new ASN1BitString(true, false, true, false, true), c.getIssuerDN(), c.getNotBeforeTime(), c.getNotAfterTime(), c.getSubjectDN(), c.getPublicKeyAlgorithmOID(), null, c.getEncodedPublicKey(), c.getDecodedPublicKey(), c.getIssuerUniqueID(), c.getSubjectUniqueID(), extensions);
    cert.verifySignature(null);
}
Also used : KeyPair(java.security.KeyPair) DN(com.unboundid.ldap.sdk.DN) OID(com.unboundid.util.OID) ASN1BitString(com.unboundid.asn1.ASN1BitString) Test(org.testng.annotations.Test)

Example 39 with ASN1BitString

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

the class PKCS10CertificateSigningRequest method generateCertificateSigningRequest.

/**
 * Generates a PKCS #10 certificate signing request 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 to use for the certificate signing
 *                             request.  This must not be {@code null}.
 * @param  subjectDN           The subject DN for the certificate signing
 *                             request.  This must not be {@code null}.
 * @param  extensions          The set of extensions to include in the
 *                             certificate signing request.  This may be
 *                             {@code null} or empty if the request should not
 *                             include any custom extensions.
 *
 * @return  The generated PKCS #10 certificate signing request.
 *
 * @throws  CertException  If a problem is encountered while creating the
 *                         certificate signing request.
 */
@NotNull()
public static PKCS10CertificateSigningRequest generateCertificateSigningRequest(@NotNull final SignatureAlgorithmIdentifier signatureAlgorithm, @NotNull final KeyPair keyPair, @NotNull final DN subjectDN, @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_CSR_GEN_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);
    final ASN1BitString encodedSignature = generateSignature(signatureAlgorithm, keyPair.getPrivate(), subjectDN, publicKeyAlgorithmOID, publicKeyAlgorithmParameters, encodedPublicKey, allExtensions);
    return new PKCS10CertificateSigningRequest(PKCS10CertificateSigningRequestVersion.V1, signatureAlgorithm.getOID(), null, encodedSignature, subjectDN, publicKeyAlgorithmOID, publicKeyAlgorithmParameters, encodedPublicKey, decodedPublicKey, null, allExtensions);
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ArrayList(java.util.ArrayList) OID(com.unboundid.util.OID) ASN1BitString(com.unboundid.asn1.ASN1BitString) ASN1Element(com.unboundid.asn1.ASN1Element) MessageDigest(java.security.MessageDigest) NotNull(com.unboundid.util.NotNull)

Example 40 with ASN1BitString

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

the class PKCS10CertificateSigningRequest method generateSignature.

/**
 * Generates a signature for the certificate signing request 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 signing request.  This
 *                                       must not be {@code null}.
 * @param  subjectDN                     The subject DN for the certificate
 *                                       signing request.  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 signing request.
 *                                       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 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_CSR_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_CSR_GEN_SIGNATURE_CANNOT_INIT_SIGNATURE_GENERATOR.get(signatureAlgorithm.getJavaName(), StaticUtils.getExceptionMessage(e)), e);
    }
    // compute its signature.
    try {
        final ArrayList<ASN1Element> requestInfoElements = new ArrayList<>(4);
        requestInfoElements.add(new ASN1Integer(PKCS10CertificateSigningRequestVersion.V1.getIntValue()));
        requestInfoElements.add(X509Certificate.encodeName(subjectDN));
        if (publicKeyAlgorithmParameters == null) {
            requestInfoElements.add(new ASN1Sequence(new ASN1Sequence(new ASN1ObjectIdentifier(publicKeyAlgorithmOID)), encodedPublicKey));
        } else {
            requestInfoElements.add(new ASN1Sequence(new ASN1Sequence(new ASN1ObjectIdentifier(publicKeyAlgorithmOID), publicKeyAlgorithmParameters), encodedPublicKey));
        }
        final ArrayList<ASN1Element> attrElements = new ArrayList<>(1);
        if ((extensions != null) && (extensions.length > 0)) {
            final ArrayList<ASN1Element> extensionElements = new ArrayList<>(extensions.length);
            for (final X509CertificateExtension e : extensions) {
                extensionElements.add(e.encode());
            }
            attrElements.add(new ASN1Sequence(new ASN1ObjectIdentifier(ATTRIBUTE_OID_EXTENSIONS), new ASN1Set(new ASN1Sequence(extensionElements))));
        }
        requestInfoElements.add(new ASN1Set(TYPE_ATTRIBUTES, attrElements));
        final byte[] certificationRequestInfoBytes = new ASN1Sequence(requestInfoElements).encode();
        signature.update(certificationRequestInfoBytes);
        final byte[] signatureBytes = signature.sign();
        return new ASN1BitString(ASN1BitString.getBitsForBytes(signatureBytes));
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new CertException(ERR_CSR_GEN_SIGNATURE_CANNOT_COMPUTE.get(signatureAlgorithm.getJavaName(), StaticUtils.getExceptionMessage(e)), e);
    }
}
Also used : ArrayList(java.util.ArrayList) ASN1Integer(com.unboundid.asn1.ASN1Integer) ASN1BitString(com.unboundid.asn1.ASN1BitString) ASN1Sequence(com.unboundid.asn1.ASN1Sequence) ASN1Set(com.unboundid.asn1.ASN1Set) Signature(java.security.Signature) ASN1Element(com.unboundid.asn1.ASN1Element) ASN1ObjectIdentifier(com.unboundid.asn1.ASN1ObjectIdentifier) NotNull(com.unboundid.util.NotNull)

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