Search in sources :

Example 36 with OID

use of com.unboundid.util.OID in project ldapsdk by pingidentity.

the class X509Certificate method toString.

/**
 * Appends a string representation of the decoded X.509 certificate to the
 * provided buffer.
 *
 * @param  buffer  The buffer to which the information should be appended.
 */
public void toString(@NotNull final StringBuilder buffer) {
    buffer.append("X509Certificate(version='");
    buffer.append(version.getName());
    buffer.append("', serialNumber='");
    StaticUtils.toHex(serialNumber.toByteArray(), ":", buffer);
    buffer.append("', signatureAlgorithmOID='");
    buffer.append(signatureAlgorithmOID.toString());
    buffer.append('\'');
    if (signatureAlgorithmName != null) {
        buffer.append(", signatureAlgorithmName='");
        buffer.append(signatureAlgorithmName);
        buffer.append('\'');
    }
    buffer.append(", issuerDN='");
    buffer.append(issuerDN.toString());
    buffer.append("', notBefore='");
    buffer.append(StaticUtils.encodeGeneralizedTime(notBefore));
    buffer.append("', notAfter='");
    buffer.append(StaticUtils.encodeGeneralizedTime(notAfter));
    buffer.append("', subjectDN='");
    buffer.append(subjectDN.toString());
    buffer.append("', publicKeyAlgorithmOID='");
    buffer.append(publicKeyAlgorithmOID.toString());
    buffer.append('\'');
    if (publicKeyAlgorithmName != null) {
        buffer.append(", publicKeyAlgorithmName='");
        buffer.append(publicKeyAlgorithmName);
        buffer.append('\'');
    }
    buffer.append(", subjectPublicKey=");
    if (decodedPublicKey == null) {
        buffer.append('\'');
        try {
            StaticUtils.toHex(encodedPublicKey.getBytes(), ":", buffer);
        } catch (final Exception e) {
            Debug.debugException(e);
            encodedPublicKey.toString(buffer);
        }
        buffer.append('\'');
    } else {
        decodedPublicKey.toString(buffer);
        if (decodedPublicKey instanceof EllipticCurvePublicKey) {
            try {
                final OID namedCurveOID = publicKeyAlgorithmParameters.decodeAsObjectIdentifier().getOID();
                buffer.append(", ellipticCurvePublicKeyParameters=namedCurve='");
                buffer.append(NamedCurve.getNameOrOID(namedCurveOID));
                buffer.append('\'');
            } catch (final Exception e) {
                Debug.debugException(e);
            }
        }
    }
    if (issuerUniqueID != null) {
        buffer.append(", issuerUniqueID='");
        buffer.append(issuerUniqueID.toString());
        buffer.append('\'');
    }
    if (subjectUniqueID != null) {
        buffer.append(", subjectUniqueID='");
        buffer.append(subjectUniqueID.toString());
        buffer.append('\'');
    }
    if (!extensions.isEmpty()) {
        buffer.append(", extensions={");
        final Iterator<X509CertificateExtension> iterator = extensions.iterator();
        while (iterator.hasNext()) {
            iterator.next().toString(buffer);
            if (iterator.hasNext()) {
                buffer.append(", ");
            }
        }
        buffer.append('}');
    }
    buffer.append(", signatureValue='");
    try {
        StaticUtils.toHex(signatureValue.getBytes(), ":", buffer);
    } catch (final Exception e) {
        Debug.debugException(e);
        buffer.append(signatureValue.toString());
    }
    buffer.append("')");
}
Also used : OID(com.unboundid.util.OID) ASN1Exception(com.unboundid.asn1.ASN1Exception) CertificateException(java.security.cert.CertificateException)

Example 37 with OID

use of com.unboundid.util.OID 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 38 with OID

use of com.unboundid.util.OID in project ldapsdk by pingidentity.

the class ManageCertificates method doCheckCertificateUsability.

/**
 * Performs the necessary processing for the check-certificate-usability
 * subcommand.
 *
 * @return  A result code that indicates whether the processing completed
 *          successfully.
 */
@NotNull()
private ResultCode doCheckCertificateUsability() {
    // Get the values of a number of configured arguments.
    final StringArgument aliasArgument = subCommandParser.getStringArgument("alias");
    final String alias = aliasArgument.getValue();
    final String keystoreType;
    final File keystorePath = getKeystorePath();
    try {
        keystoreType = inferKeystoreType(keystorePath);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    final char[] keystorePassword;
    try {
        keystorePassword = getKeystorePassword(keystorePath);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    // Get the keystore.
    final KeyStore keystore;
    try {
        keystore = getKeystore(keystoreType, keystorePath, keystorePassword);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    // Make sure that the specified entry exists in the keystore and is
    // associated with a certificate chain and a private key.
    final X509Certificate[] chain;
    if (hasKeyAlias(keystore, alias)) {
        try {
            final Certificate[] genericChain = keystore.getCertificateChain(alias);
            Validator.ensureTrue((genericChain.length > 0), "ERROR:  The keystore has a private key entry for alias '" + alias + "', but the associated certificate chain is empty.");
            chain = new X509Certificate[genericChain.length];
            for (int i = 0; i < genericChain.length; i++) {
                chain[i] = new X509Certificate(genericChain[i].getEncoded());
            }
            out();
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_GOT_CHAIN.get(alias));
            for (final X509Certificate c : chain) {
                out();
                printCertificate(c, "", false);
            }
        } catch (final Exception e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_CANNOT_GET_CHAIN.get(alias));
            e.printStackTrace(getErr());
            return ResultCode.LOCAL_ERROR;
        }
    } else if (hasCertificateAlias(keystore, alias)) {
        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_NO_PRIVATE_KEY.get(alias));
        return ResultCode.PARAM_ERROR;
    } else {
        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_NO_SUCH_ALIAS.get(alias));
        return ResultCode.PARAM_ERROR;
    }
    // Check to see if the certificate is self-signed.  If so, then that's a
    // warning.  If not, then make sure that the chain is complete and that each
    // subsequent certificate is the issuer of the previous.
    int numWarnings = 0;
    int numErrors = 0;
    if (chain[0].isSelfSigned()) {
        err();
        wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_CERT_IS_SELF_SIGNED.get(chain[0].getSubjectDN()));
        numWarnings++;
    } else if ((chain.length == 1) || (!chain[chain.length - 1].isSelfSigned())) {
        err();
        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_END_OF_CHAIN_NOT_SELF_SIGNED.get(alias));
        numErrors++;
    } else {
        boolean chainError = false;
        final StringBuilder nonMatchReason = new StringBuilder();
        for (int i = 1; i < chain.length; i++) {
            if (!chain[i].isIssuerFor(chain[i - 1], nonMatchReason)) {
                err();
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_CHAIN_ISSUER_MISMATCH.get(alias, chain[i].getSubjectDN(), chain[i - 1].getSubjectDN(), nonMatchReason));
                numErrors++;
                chainError = true;
            }
        }
        if (!chainError) {
            out();
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_CHAIN_COMPLETE.get());
        }
    }
    // display a notice, but we won't consider it a warning in and of itself.
    if ((chain.length > 1) && chain[chain.length - 1].isSelfSigned()) {
        final X509Certificate caCert = chain[chain.length - 1];
        try {
            final String jvmDefaultTrustStoreType = inferKeystoreType(JVM_DEFAULT_CACERTS_FILE);
            final KeyStore jvmDefaultTrustStore = CryptoHelper.getKeyStore(jvmDefaultTrustStoreType);
            try (FileInputStream inputStream = new FileInputStream(JVM_DEFAULT_CACERTS_FILE)) {
                jvmDefaultTrustStore.load(inputStream, null);
            }
            boolean found = false;
            final Enumeration<String> aliases = jvmDefaultTrustStore.aliases();
            while (aliases.hasMoreElements()) {
                final String jvmDefaultCertAlias = aliases.nextElement();
                if (jvmDefaultTrustStore.isCertificateEntry(jvmDefaultCertAlias)) {
                    final Certificate c = jvmDefaultTrustStore.getCertificate(jvmDefaultCertAlias);
                    final X509Certificate xc = new X509Certificate(c.getEncoded());
                    if ((caCert.getSubjectDN().equals(xc.getSubjectDN())) && Arrays.equals(caCert.getSignatureValue().getBits(), xc.getSignatureValue().getBits())) {
                        found = true;
                        break;
                    }
                }
            }
            if (found) {
                out();
                wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_CA_TRUSTED_OK.get(caCert.getSubjectDN()));
            } else {
                out();
                wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_CA_NOT_IN_JVM_DEFAULT_TS.get(caCert.getSubjectDN()));
            }
        } catch (final Exception e) {
            Debug.debugException(e);
            err();
            wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_CHECK_CA_IN_TS_ERROR.get(caCert.getSubjectDN(), StaticUtils.getExceptionMessage(e)));
            numWarnings++;
        }
    }
    // error.
    for (int i = 0; i < chain.length; i++) {
        final X509Certificate c = chain[i];
        try {
            if (c.isSelfSigned()) {
                c.verifySignature(null);
            } else if ((i + 1) < chain.length) {
                c.verifySignature(chain[i + 1]);
            }
            out();
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_CERT_SIGNATURE_VALID.get(c.getSubjectDN()));
        } catch (final CertException ce) {
            err();
            wrapErr(0, WRAP_COLUMN, ce.getMessage());
            numErrors++;
        }
    }
    // Check the validity window for each certificate in the chain.  If any of
    // them is expired or not yet valid, then that's an error.  If any of them
    // will expire in the near future, then that's a warning.
    final long currentTime = System.currentTimeMillis();
    final long thirtyDaysFromNow = currentTime + (30L * 24L * 60L * 60L * 1000L);
    for (int i = 0; i < chain.length; i++) {
        final X509Certificate c = chain[i];
        if (c.getNotBeforeTime() > currentTime) {
            err();
            if (i == 0) {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_END_CERT_NOT_YET_VALID.get(c.getSubjectDN(), formatDateAndTime(c.getNotBeforeDate())));
            } else {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_ISSUER_CERT_NOT_YET_VALID.get(c.getSubjectDN(), formatDateAndTime(c.getNotBeforeDate())));
            }
            numErrors++;
        } else if (c.getNotAfterTime() < currentTime) {
            err();
            if (i == 0) {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_END_CERT_EXPIRED.get(c.getSubjectDN(), formatDateAndTime(c.getNotAfterDate())));
            } else {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_ISSUER_CERT_EXPIRED.get(c.getSubjectDN(), formatDateAndTime(c.getNotAfterDate())));
            }
            numErrors++;
        } else if (c.getNotAfterTime() < thirtyDaysFromNow) {
            err();
            if (i == 0) {
                wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_END_CERT_NEAR_EXPIRATION.get(c.getSubjectDN(), formatDateAndTime(c.getNotAfterDate())));
            } else {
                wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_ISSUER_CERT_NEAR_EXPIRATION.get(c.getSubjectDN(), formatDateAndTime(c.getNotAfterDate())));
            }
            numWarnings++;
        } else {
            if (i == 0) {
                out();
                wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_END_CERT_VALIDITY_OK.get(c.getSubjectDN(), formatDateAndTime(c.getNotAfterDate())));
            } else {
                out();
                wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_ISSUER_CERT_VALIDITY_OK.get(c.getSubjectDN(), formatDateAndTime(c.getNotAfterDate())));
            }
        }
    }
    // determine whether the certificate has been revoked.
    for (int i = 0; i < chain.length; i++) {
        boolean basicConstraintsFound = false;
        boolean extendedKeyUsageFound = false;
        boolean keyUsageFound = false;
        final X509Certificate c = chain[i];
        for (final X509CertificateExtension extension : c.getExtensions()) {
            if (extension instanceof ExtendedKeyUsageExtension) {
                extendedKeyUsageFound = true;
                if (i == 0) {
                    final ExtendedKeyUsageExtension e = (ExtendedKeyUsageExtension) extension;
                    if (!e.getKeyPurposeIDs().contains(ExtendedKeyUsageID.TLS_SERVER_AUTHENTICATION.getOID())) {
                        err();
                        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_END_CERT_BAD_EKU.get(c.getSubjectDN()));
                        numErrors++;
                    } else {
                        out();
                        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_END_CERT_GOOD_EKU.get(c.getSubjectDN()));
                    }
                }
            } else if (extension instanceof BasicConstraintsExtension) {
                basicConstraintsFound = true;
                if (i > 0) {
                    final BasicConstraintsExtension e = (BasicConstraintsExtension) extension;
                    if (!e.isCA()) {
                        err();
                        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_ISSUER_CERT_BAD_BC_CA.get(c.getSubjectDN()));
                        numErrors++;
                    } else if ((e.getPathLengthConstraint() != null) && ((i - 1) > e.getPathLengthConstraint())) {
                        err();
                        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_ISSUER_CERT_BAD_BC_LENGTH.get(c.getSubjectDN(), e.getPathLengthConstraint(), chain[0].getSubjectDN(), (i - 1)));
                        numErrors++;
                    } else {
                        out();
                        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_ISSUER_CERT_GOOD_BC.get(c.getSubjectDN()));
                    }
                }
            } else if (extension instanceof KeyUsageExtension) {
                keyUsageFound = true;
                if (i > 0) {
                    final KeyUsageExtension e = (KeyUsageExtension) extension;
                    if (!e.isKeyCertSignBitSet()) {
                        err();
                        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_ISSUER_NO_CERT_SIGN_KU.get(c.getSubjectDN()));
                        numErrors++;
                    } else {
                        out();
                        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_ISSUER_GOOD_KU.get(c.getSubjectDN()));
                    }
                }
            }
        }
        if (i == 0) {
            if (!extendedKeyUsageFound) {
                err();
                wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_NO_EKU.get(c.getSubjectDN()));
                numWarnings++;
            }
        } else {
            if (!basicConstraintsFound) {
                err();
                wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_NO_BC.get(c.getSubjectDN()));
                numWarnings++;
            }
            if (!keyUsageFound) {
                err();
                wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_NO_KU.get(c.getSubjectDN()));
                numWarnings++;
            }
        }
    }
    // Make sure that none of the certificates has a signature algorithm that
    // uses MD5 or SHA-1.  If it uses an unrecognized signature algorithm, then
    // that's a warning.
    boolean isIssuer = false;
    final BooleanArgument ignoreSHA1WarningArg = subCommandParser.getBooleanArgument("allow-sha-1-signature-for-issuer-certificates");
    final boolean ignoreSHA1SignatureWarningForIssuerCertificates = ((ignoreSHA1WarningArg != null) && ignoreSHA1WarningArg.isPresent());
    for (final X509Certificate c : chain) {
        final OID signatureAlgorithmOID = c.getSignatureAlgorithmOID();
        final SignatureAlgorithmIdentifier id = SignatureAlgorithmIdentifier.forOID(signatureAlgorithmOID);
        if (id == null) {
            err();
            wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_UNKNOWN_SIG_ALG.get(c.getSubjectDN(), signatureAlgorithmOID));
            numWarnings++;
        } else {
            switch(id) {
                case MD2_WITH_RSA:
                case MD5_WITH_RSA:
                    err();
                    wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_WEAK_SIG_ALG.get(c.getSubjectDN(), id.getUserFriendlyName()));
                    numErrors++;
                    break;
                case SHA_1_WITH_RSA:
                case SHA_1_WITH_DSA:
                case SHA_1_WITH_ECDSA:
                    if (isIssuer && ignoreSHA1SignatureWarningForIssuerCertificates) {
                        err();
                        wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_ISSUER_WITH_SHA1_SIG.get(c.getSubjectDN(), id.getUserFriendlyName(), ignoreSHA1WarningArg.getIdentifierString()));
                    } else {
                        err();
                        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_WEAK_SIG_ALG.get(c.getSubjectDN(), id.getUserFriendlyName()));
                        numErrors++;
                    }
                    break;
                case SHA_224_WITH_RSA:
                case SHA_224_WITH_DSA:
                case SHA_224_WITH_ECDSA:
                case SHA_256_WITH_RSA:
                case SHA_256_WITH_DSA:
                case SHA_256_WITH_ECDSA:
                case SHA_384_WITH_RSA:
                case SHA_384_WITH_ECDSA:
                case SHA_512_WITH_RSA:
                case SHA_512_WITH_ECDSA:
                    out();
                    wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_SIG_ALG_OK.get(c.getSubjectDN(), id.getUserFriendlyName()));
                    break;
            }
        }
        isIssuer = true;
    }
    // has a public modulus size smaller than 2048 bits.
    for (final X509Certificate c : chain) {
        if ((c.getDecodedPublicKey() != null) && (c.getDecodedPublicKey() instanceof RSAPublicKey)) {
            final RSAPublicKey rsaPublicKey = (RSAPublicKey) c.getDecodedPublicKey();
            final byte[] modulusBytes = rsaPublicKey.getModulus().toByteArray();
            int modulusSizeBits = modulusBytes.length * 8;
            if (((modulusBytes.length % 2) != 0) && (modulusBytes[0] == 0x00)) {
                modulusSizeBits -= 8;
            }
            if (modulusSizeBits < 2048) {
                err();
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_WEAK_RSA_MODULUS.get(c.getSubjectDN(), modulusSizeBits));
                numErrors++;
            } else {
                out();
                wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_RSA_MODULUS_OK.get(c.getSubjectDN(), modulusSizeBits));
            }
        }
    }
    switch(numErrors) {
        case 0:
            break;
        case 1:
            err();
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_ONE_ERROR.get());
            return ResultCode.PARAM_ERROR;
        default:
            err();
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_MULTIPLE_ERRORS.get(numErrors));
            return ResultCode.PARAM_ERROR;
    }
    switch(numWarnings) {
        case 0:
            out();
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_NO_ERRORS_OR_WARNINGS.get());
            return ResultCode.SUCCESS;
        case 1:
            err();
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_ONE_WARNING.get());
            return ResultCode.PARAM_ERROR;
        default:
            err();
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_MULTIPLE_WARNINGS.get(numWarnings));
            return ResultCode.PARAM_ERROR;
    }
}
Also used : ASN1BitString(com.unboundid.asn1.ASN1BitString) BooleanArgument(com.unboundid.util.args.BooleanArgument) OID(com.unboundid.util.OID) KeyStore(java.security.KeyStore) ArgumentException(com.unboundid.util.args.ArgumentException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) StringArgument(com.unboundid.util.args.StringArgument) LDAPException(com.unboundid.ldap.sdk.LDAPException) File(java.io.File) Certificate(java.security.cert.Certificate) NotNull(com.unboundid.util.NotNull)

Example 39 with OID

use of com.unboundid.util.OID in project ldapsdk by pingidentity.

the class PKCS10CertificateSigningRequest method toString.

/**
 * Appends a string representation of the decoded X.509 certificate to the
 * provided buffer.
 *
 * @param  buffer  The buffer to which the information should be appended.
 */
public void toString(@NotNull final StringBuilder buffer) {
    buffer.append("PKCS10CertificateSigningRequest(version='");
    buffer.append(version.getName());
    buffer.append("', subjectDN='");
    buffer.append(subjectDN);
    buffer.append("', publicKeyAlgorithmOID='");
    buffer.append(publicKeyAlgorithmOID.toString());
    buffer.append('\'');
    if (publicKeyAlgorithmName != null) {
        buffer.append(", publicKeyAlgorithmName='");
        buffer.append(publicKeyAlgorithmName);
        buffer.append('\'');
    }
    buffer.append(", subjectPublicKey=");
    if (decodedPublicKey == null) {
        buffer.append('\'');
        try {
            StaticUtils.toHex(encodedPublicKey.getBytes(), ":", buffer);
        } catch (final Exception e) {
            Debug.debugException(e);
            encodedPublicKey.toString(buffer);
        }
        buffer.append('\'');
    } else {
        decodedPublicKey.toString(buffer);
        if (decodedPublicKey instanceof EllipticCurvePublicKey) {
            try {
                final OID namedCurveOID = publicKeyAlgorithmParameters.decodeAsObjectIdentifier().getOID();
                buffer.append(", ellipticCurvePublicKeyParameters=namedCurve='");
                buffer.append(NamedCurve.getNameOrOID(namedCurveOID));
                buffer.append('\'');
            } catch (final Exception e) {
                Debug.debugException(e);
            }
        }
    }
    buffer.append(", signatureAlgorithmOID='");
    buffer.append(signatureAlgorithmOID.toString());
    buffer.append('\'');
    if (signatureAlgorithmName != null) {
        buffer.append(", signatureAlgorithmName='");
        buffer.append(signatureAlgorithmName);
        buffer.append('\'');
    }
    if (!extensions.isEmpty()) {
        buffer.append(", extensions={");
        final Iterator<X509CertificateExtension> iterator = extensions.iterator();
        while (iterator.hasNext()) {
            iterator.next().toString(buffer);
            if (iterator.hasNext()) {
                buffer.append(", ");
            }
        }
        buffer.append('}');
    }
    buffer.append(", signatureValue='");
    try {
        StaticUtils.toHex(signatureValue.getBytes(), ":", buffer);
    } catch (final Exception e) {
        Debug.debugException(e);
        buffer.append(signatureValue.toString());
    }
    buffer.append("')");
}
Also used : OID(com.unboundid.util.OID)

Example 40 with OID

use of com.unboundid.util.OID in project ldapsdk by pingidentity.

the class PKCS10CertificateSigningRequest method encode.

/**
 * Encodes this PKCS #10 certificate signing request to an ASN.1 element.
 *
 * @return  The encoded PKCS #10 certificate signing request.
 *
 * @throws  CertException  If a problem is encountered while trying to encode
 *                         the PKCS #10 certificate signing request.
 */
@NotNull()
private ASN1Element encode() throws CertException {
    try {
        final ArrayList<ASN1Element> requestInfoElements = new ArrayList<>(4);
        requestInfoElements.add(new ASN1Integer(version.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<>(requestAttributes.size());
        for (final ObjectPair<OID, ASN1Set> attr : requestAttributes) {
            attrElements.add(new ASN1Sequence(new ASN1ObjectIdentifier(attr.getFirst()), attr.getSecond()));
        }
        requestInfoElements.add(new ASN1Set(TYPE_ATTRIBUTES, attrElements));
        final ArrayList<ASN1Element> certificationRequestElements = new ArrayList<>(3);
        certificationRequestElements.add(new ASN1Sequence(requestInfoElements));
        if (signatureAlgorithmParameters == null) {
            certificationRequestElements.add(new ASN1Sequence(new ASN1ObjectIdentifier(signatureAlgorithmOID)));
        } else {
            certificationRequestElements.add(new ASN1Sequence(new ASN1ObjectIdentifier(signatureAlgorithmOID), signatureAlgorithmParameters));
        }
        certificationRequestElements.add(signatureValue);
        return new ASN1Sequence(certificationRequestElements);
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new CertException(ERR_CSR_ENCODE_ERROR.get(toString(), StaticUtils.getExceptionMessage(e)), e);
    }
}
Also used : ASN1Sequence(com.unboundid.asn1.ASN1Sequence) ASN1Set(com.unboundid.asn1.ASN1Set) ASN1Element(com.unboundid.asn1.ASN1Element) ArrayList(java.util.ArrayList) ASN1Integer(com.unboundid.asn1.ASN1Integer) OID(com.unboundid.util.OID) ASN1ObjectIdentifier(com.unboundid.asn1.ASN1ObjectIdentifier) NotNull(com.unboundid.util.NotNull)

Aggregations

OID (com.unboundid.util.OID)66 Test (org.testng.annotations.Test)53 ASN1BitString (com.unboundid.asn1.ASN1BitString)38 DN (com.unboundid.ldap.sdk.DN)38 ASN1Null (com.unboundid.asn1.ASN1Null)32 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)30 ASN1ObjectIdentifier (com.unboundid.asn1.ASN1ObjectIdentifier)25 ASN1Sequence (com.unboundid.asn1.ASN1Sequence)23 ASN1Element (com.unboundid.asn1.ASN1Element)21 ASN1Integer (com.unboundid.asn1.ASN1Integer)18 ASN1BigInteger (com.unboundid.asn1.ASN1BigInteger)16 ASN1GeneralizedTime (com.unboundid.asn1.ASN1GeneralizedTime)9 NotNull (com.unboundid.util.NotNull)8 ArrayList (java.util.ArrayList)7 ASN1UTCTime (com.unboundid.asn1.ASN1UTCTime)6 Date (java.util.Date)6 ASN1Set (com.unboundid.asn1.ASN1Set)4 RDN (com.unboundid.ldap.sdk.RDN)4 File (java.io.File)4 KeyPair (java.security.KeyPair)4