java.security.cert.CertificateParsingException Java Examples

The following examples show how to use java.security.cert.CertificateParsingException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: X509Utils.java    From bcm-android with GNU General Public License v3.0 7 votes vote down vote up
/**
 * Returns either a string that "sums up" the certificate for humans, in a similar manner to what you might see
 * in a web browser, or null if one cannot be extracted. This will typically be the common name (CN) field, but
 * can also be the org (O) field, org+location+country if withLocation is set, or the email
 * address for S/MIME certificates.
 */
@Nullable
public static String getDisplayNameFromCertificate(@Nonnull X509Certificate certificate, boolean withLocation) throws CertificateParsingException {
    X500Name name = new X500Name(certificate.getSubjectX500Principal().getName());
    String commonName = null, org = null, location = null, country = null;
    for (RDN rdn : name.getRDNs()) {
        AttributeTypeAndValue pair = rdn.getFirst();
        String val = ((ASN1String) pair.getValue()).getString();
        ASN1ObjectIdentifier type = pair.getType();
        if (type.equals(RFC4519Style.cn))
            commonName = val;
        else if (type.equals(RFC4519Style.o))
            org = val;
        else if (type.equals(RFC4519Style.l))
            location = val;
        else if (type.equals(RFC4519Style.c))
            country = val;
    }
    final Collection<List<?>> subjectAlternativeNames = certificate.getSubjectAlternativeNames();
    String altName = null;
    if (subjectAlternativeNames != null)
        for (final List<?> subjectAlternativeName : subjectAlternativeNames)
            if ((Integer) subjectAlternativeName.get(0) == 1) // rfc822name
                altName = (String) subjectAlternativeName.get(1);

    if (org != null) {
        return withLocation ? Joiner.on(", ").skipNulls().join(org, location, country) : org;
    } else if (commonName != null) {
        return commonName;
    } else {
        return altName;
    }
}
 
Example #2
Source File: CertificateUtils.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of subject alternative names. Any name that is represented as a String by X509Certificate.getSubjectAlternativeNames() is converted to lowercase and returned.
 *
 * @param certificate a certificate
 * @return a list of subject alternative names; list is never null
 * @throws CertificateParsingException if parsing the certificate failed
 */
public static List<String> getSubjectAlternativeNames(final X509Certificate certificate) throws CertificateParsingException {

    final Collection<List<?>> altNames = certificate.getSubjectAlternativeNames();
    if (altNames == null) {
        return new ArrayList<>();
    }

    final List<String> result = new ArrayList<>();
    for (final List<?> generalName : altNames) {
        /**
         * generalName has the name type as the first element a String or byte array for the second element. We return any general names that are String types.
         *
         * We don't inspect the numeric name type because some certificates incorrectly put IPs and DNS names under the wrong name types.
         */
        final Object value = generalName.get(1);
        if (value instanceof String) {
            result.add(((String) value).toLowerCase());
        }

    }

    return result;
}
 
Example #3
Source File: CertificateFactory.java    From ripple-lib-java with ISC License 6 votes vote down vote up
private java.security.cert.Certificate readDERCertificate(
    ASN1InputStream dIn)
    throws IOException, CertificateParsingException
{
    ASN1Sequence seq = (ASN1Sequence)dIn.readObject();

    if (seq.size() > 1
            && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier)
    {
        if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
        {
            sData = SignedData.getInstance(ASN1Sequence.getInstance(
                (ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates();

            return getCertificate();
        }
    }

    return new X509CertificateObject(
                        Certificate.getInstance(seq));
}
 
Example #4
Source File: Asn1Utils.java    From Auditor with MIT License 6 votes vote down vote up
public static ASN1Sequence getAsn1SequenceFromStream(final ASN1InputStream asn1InputStream)
        throws IOException, CertificateParsingException {
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    if (!(asn1Primitive instanceof ASN1OctetString)) {
        throw new CertificateParsingException(
                "Expected octet stream, found " + asn1Primitive.getClass().getName());
    }
    try (ASN1InputStream seqInputStream = new ASN1InputStream(
            ((ASN1OctetString) asn1Primitive).getOctets())) {
        asn1Primitive = seqInputStream.readObject();
        if (!(asn1Primitive instanceof ASN1Sequence)) {
            throw new CertificateParsingException(
                    "Expected sequence, found " + asn1Primitive.getClass().getName());
        }
        return (ASN1Sequence) asn1Primitive;
    }
}
 
Example #5
Source File: CertificateFactory.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
private java.security.cert.Certificate readDERCertificate(
    ASN1InputStream dIn)
    throws IOException, CertificateParsingException
{
    ASN1Sequence seq = (ASN1Sequence)dIn.readObject();

    if (seq.size() > 1
            && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier)
    {
        if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
        {
            sData = SignedData.getInstance(ASN1Sequence.getInstance(
                (ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates();

            return getCertificate();
        }
    }

    return new X509CertificateObject(
                        Certificate.getInstance(seq));
}
 
Example #6
Source File: X509CertParser.java    From ripple-lib-java with ISC License 6 votes vote down vote up
private Certificate readDERCertificate(
    InputStream in)
    throws IOException, CertificateParsingException
{
    ASN1InputStream dIn = new ASN1InputStream(in);
    ASN1Sequence seq = (ASN1Sequence)dIn.readObject();

    if (seq.size() > 1
            && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier)
    {
        if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
        {
            sData = new SignedData(ASN1Sequence.getInstance(
                            (ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates();

            return getCertificate();
        }
    }

    return new X509CertificateObject(
                        org.ripple.bouncycastle.asn1.x509.Certificate.getInstance(seq));
}
 
Example #7
Source File: RootOfTrust.java    From Auditor with MIT License 6 votes vote down vote up
public RootOfTrust(ASN1Encodable asn1Encodable) throws CertificateParsingException {
    if (!(asn1Encodable instanceof ASN1Sequence)) {
        throw new CertificateParsingException("Expected sequence for root of trust, found "
                + asn1Encodable.getClass().getName());
    }

    ASN1Sequence sequence = (ASN1Sequence) asn1Encodable;
    verifiedBootKey =
            Asn1Utils.getByteArrayFromAsn1(sequence.getObjectAt(VERIFIED_BOOT_KEY_INDEX));
    deviceLocked = Asn1Utils.getBooleanFromAsn1(sequence.getObjectAt(DEVICE_LOCKED_INDEX));
    verifiedBootState =
            Asn1Utils.getIntegerFromAsn1(sequence.getObjectAt(VERIFIED_BOOT_STATE_INDEX));
    if (sequence.size() < 4) {
        verifiedBootHash = null;
        return;
    }
    verifiedBootHash =
            Asn1Utils.getByteArrayFromAsn1(sequence.getObjectAt(VERIFIED_BOOT_HASH_INDEX));
}
 
Example #8
Source File: AttestationPackageInfo.java    From Auditor with MIT License 6 votes vote down vote up
public AttestationPackageInfo(ASN1Encodable asn1Encodable) throws CertificateParsingException {
    if (!(asn1Encodable instanceof ASN1Sequence)) {
        throw new CertificateParsingException(
                "Expected sequence for AttestationPackageInfo, found "
                        + asn1Encodable.getClass().getName());
    }

    ASN1Sequence sequence = (ASN1Sequence) asn1Encodable;
    try {
        packageName = Asn1Utils.getStringFromAsn1OctetStreamAssumingUTF8(
                sequence.getObjectAt(PACKAGE_NAME_INDEX));
    } catch (UnsupportedEncodingException e) {
        throw new CertificateParsingException(
                "Converting octet stream to String triggered an UnsupportedEncodingException",
                e);
    }
    version = Asn1Utils.getLongFromAsn1(sequence.getObjectAt(VERSION_INDEX));
}
 
Example #9
Source File: X509V3CertificateGenerator.java    From ripple-lib-java with ISC License 6 votes vote down vote up
/**
 * add a given extension field for the standard extensions tag (tag 3)
 * copying the extension value from another certificate.
 * @throws CertificateParsingException if the extension cannot be extracted.
 */
public void copyAndAddExtension(
    String          oid,
    boolean         critical,
    X509Certificate cert) 
    throws CertificateParsingException
{
    byte[] extValue = cert.getExtensionValue(oid);
    
    if (extValue == null)
    {
        throw new CertificateParsingException("extension " + oid + " not present");
    }
    
    try
    {
        ASN1Encodable value = X509ExtensionUtil.fromExtensionValue(extValue);

        this.addExtension(oid, critical, value);
    }
    catch (IOException e)
    {
        throw new CertificateParsingException(e.toString());
    }
}
 
Example #10
Source File: X509V1CertificateGenerator.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
private X509Certificate generateJcaObject(TBSCertificate tbsCert, byte[] signature)
    throws CertificateEncodingException
{
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(sigAlgId);
    v.add(new DERBitString(signature));

    try
    {
        return new X509CertificateObject(Certificate.getInstance(new DERSequence(v)));
    }
    catch (CertificateParsingException e)
    {
        throw new ExtCertificateEncodingException("exception producing certificate object", e);
    }
}
 
Example #11
Source File: CertificateValidationUtil.java    From opc-ua-stack with Apache License 2.0 6 votes vote down vote up
public static boolean validateSubjectAltNameField(X509Certificate certificate, int field,
                                                  Predicate<Object> fieldValidator) throws UaException {

    try {
        Collection<List<?>> subjectAltNames = certificate.getSubjectAlternativeNames();
        if (subjectAltNames == null) subjectAltNames = Collections.emptyList();

        for (List<?> idAndValue : subjectAltNames) {
            if (idAndValue != null && idAndValue.size() == 2) {
                if (idAndValue.get(0).equals(field)) {
                    if (fieldValidator.test(idAndValue.get(1))) {
                        return true;
                    }
                }
            }
        }

        return false;
    } catch (CertificateParsingException e) {
        throw new UaException(StatusCodes.Bad_CertificateInvalid, e);
    }
}
 
Example #12
Source File: X509CertUtilsTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testExtractRequestInstanceId() throws CertificateParsingException {

    assertNull(X509CertUtils.extractRequestInstanceId(null));

    X509Certificate cert = Mockito.mock(X509Certificate.class);
    Collection<List<?>> dnsNames = new ArrayList<>();
    ArrayList<Object> item1 = new ArrayList<>();
    item1.add(2);
    item1.add("host1.domain.athenz");
    dnsNames.add(item1);
    Mockito.when(cert.getSubjectAlternativeNames()).thenReturn(dnsNames);

    assertNull(X509CertUtils.extractRequestInstanceId(cert));

    ArrayList<Object> item2 = new ArrayList<>();
    item2.add(2);
    item2.add("instanceid1.instanceid.athenz.test");
    dnsNames.add(item2);

    assertEquals("instanceid1", X509CertUtils.extractRequestInstanceId(cert));
}
 
Example #13
Source File: CertificateUtils.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of subject alternative names. Any name that is represented as a String by X509Certificate.getSubjectAlternativeNames() is converted to lowercase and returned.
 *
 * @param certificate a certificate
 * @return a list of subject alternative names; list is never null
 * @throws CertificateParsingException if parsing the certificate failed
 */
public static List<String> getSubjectAlternativeNames(final X509Certificate certificate) throws CertificateParsingException {

    final Collection<List<?>> altNames = certificate.getSubjectAlternativeNames();
    if (altNames == null) {
        return new ArrayList<>();
    }

    final List<String> result = new ArrayList<>();
    for (final List<?> generalName : altNames) {
        /**
         * generalName has the name type as the first element a String or byte array for the second element. We return any general names that are String types.
         *
         * We don't inspect the numeric name type because some certificates incorrectly put IPs and DNS names under the wrong name types.
         */
        final Object value = generalName.get(1);
        if (value instanceof String) {
            result.add(((String) value).toLowerCase());
        }

    }

    return result;
}
 
Example #14
Source File: AttestationPackageInfo.java    From AttestationServer with MIT License 6 votes vote down vote up
public AttestationPackageInfo(ASN1Encodable asn1Encodable) throws CertificateParsingException {
    if (!(asn1Encodable instanceof ASN1Sequence)) {
        throw new CertificateParsingException(
                "Expected sequence for AttestationPackageInfo, found "
                        + asn1Encodable.getClass().getName());
    }

    ASN1Sequence sequence = (ASN1Sequence) asn1Encodable;
    try {
        packageName = Asn1Utils.getStringFromAsn1OctetStreamAssumingUTF8(
                sequence.getObjectAt(PACKAGE_NAME_INDEX));
    } catch (UnsupportedEncodingException e) {
        throw new CertificateParsingException(
                "Converting octet stream to String triggered an UnsupportedEncodingException",
                e);
    }
    version = Asn1Utils.getLongFromAsn1(sequence.getObjectAt(VERSION_INDEX));
}
 
Example #15
Source File: NiFiClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verify(final String hostname, final SSLSession ssls) {
    try {
        for (final Certificate peerCertificate : ssls.getPeerCertificates()) {
            if (peerCertificate instanceof X509Certificate) {
                final X509Certificate x509Cert = (X509Certificate) peerCertificate;
                final List<String> subjectAltNames = getSubjectAlternativeNames(x509Cert);
                if (subjectAltNames.contains(hostname.toLowerCase())) {
                    return true;
                }
            }
        }
    } catch (final SSLPeerUnverifiedException | CertificateParsingException ex) {
        LOG.warn("Hostname Verification encountered exception verifying hostname due to: " + ex, ex);
    }

    return false;
}
 
Example #16
Source File: X509CertParser.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
private Certificate readDERCertificate(
    InputStream in)
    throws IOException, CertificateParsingException
{
    ASN1InputStream dIn = new ASN1InputStream(in);
    ASN1Sequence seq = (ASN1Sequence)dIn.readObject();

    if (seq.size() > 1
            && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier)
    {
        if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
        {
            sData = new SignedData(ASN1Sequence.getInstance(
                            (ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates();

            return getCertificate();
        }
    }

    return new X509CertificateObject(
                        org.ripple.bouncycastle.asn1.x509.Certificate.getInstance(seq));
}
 
Example #17
Source File: CertificateUtils.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of subject alternative names. Any name that is represented as a String by X509Certificate.getSubjectAlternativeNames() is converted to lowercase and returned.
 *
 * @param certificate a certificate
 * @return a list of subject alternative names; list is never null
 * @throws CertificateParsingException if parsing the certificate failed
 */
public static List<String> getSubjectAlternativeNames(final X509Certificate certificate) throws CertificateParsingException {

    final Collection<List<?>> altNames = certificate.getSubjectAlternativeNames();
    if (altNames == null) {
        return new ArrayList<>();
    }

    final List<String> result = new ArrayList<>();
    for (final List<?> generalName : altNames) {
        /**
         * generalName has the name type as the first element a String or byte array for the second element. We return any general names that are String types.
         *
         * We don't inspect the numeric name type because some certificates incorrectly put IPs and DNS names under the wrong name types.
         */
        final Object value = generalName.get(1);
        if (value instanceof String) {
            result.add(((String) value).toLowerCase());
        }

    }

    return result;
}
 
Example #18
Source File: PrivateKeyUsageExtension.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create the extension from the passed DER encoded value.
 *
 * @param critical true if the extension is to be treated as critical.
 * @param value an array of DER encoded bytes of the actual value.
 * @exception ClassCastException if value is not an array of bytes
 * @exception CertificateException on certificate parsing errors.
 * @exception IOException on error.
 */
public PrivateKeyUsageExtension(Boolean critical, Object value)
throws CertificateException, IOException {
    this.extensionId = PKIXExtensions.PrivateKeyUsage_Id;
    this.critical = critical.booleanValue();

    this.extensionValue = (byte[]) value;
    DerInputStream str = new DerInputStream(this.extensionValue);
    DerValue[] seq = str.getSequence(2);

    // NB. this is always encoded with the IMPLICIT tag
    // The checks only make sense if we assume implicit tagging,
    // with explicit tagging the form is always constructed.
    for (int i = 0; i < seq.length; i++) {
        DerValue opt = seq[i];

        if (opt.isContextSpecific(TAG_BEFORE) &&
            !opt.isConstructed()) {
            if (notBefore != null) {
                throw new CertificateParsingException(
                    "Duplicate notBefore in PrivateKeyUsage.");
            }
            opt.resetTag(DerValue.tag_GeneralizedTime);
            str = new DerInputStream(opt.toByteArray());
            notBefore = str.getGeneralizedTime();

        } else if (opt.isContextSpecific(TAG_AFTER) &&
                   !opt.isConstructed()) {
            if (notAfter != null) {
                throw new CertificateParsingException(
                    "Duplicate notAfter in PrivateKeyUsage.");
            }
            opt.resetTag(DerValue.tag_GeneralizedTime);
            str = new DerInputStream(opt.toByteArray());
            notAfter = str.getGeneralizedTime();
        } else
            throw new IOException("Invalid encoding of " +
                                  "PrivateKeyUsageExtension");
    }
}
 
Example #19
Source File: AuthorizationList.java    From android-testdpc with Apache License 2.0 5 votes vote down vote up
public Set<String> getPaddingModesAsStrings() throws CertificateParsingException {
    if (paddingModes == null) {
        return ImmutableSet.of();
    }

    ImmutableSet.Builder<String> builder = ImmutableSet.builder();
    for (int paddingMode : paddingModes) {
        switch (paddingMode) {
            case KM_PAD_NONE:
                builder.add(KeyProperties.ENCRYPTION_PADDING_NONE);
                break;
            case KM_PAD_RSA_OAEP:
                builder.add(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP);
                break;
            case KM_PAD_RSA_PKCS1_1_5_ENCRYPT:
                builder.add(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1);
                break;
            case KM_PAD_RSA_PKCS1_1_5_SIGN:
                builder.add(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1);
                break;
            case KM_PAD_RSA_PSS:
                builder.add(KeyProperties.SIGNATURE_PADDING_RSA_PSS);
                break;
            default:
                throw new CertificateParsingException("Invalid padding mode " + paddingMode);
        }
    }
    return builder.build();
}
 
Example #20
Source File: Asn1Utils.java    From Auditor with MIT License 5 votes vote down vote up
public static ASN1Sequence getAsn1SequenceFromBytes(byte[] bytes)
        throws CertificateParsingException {
    try (ASN1InputStream asn1InputStream = new ASN1InputStream(bytes)) {
        return getAsn1SequenceFromStream(asn1InputStream);
    } catch (IOException e) {
        throw new CertificateParsingException("Failed to parse SEQUENCE", e);
    }
}
 
Example #21
Source File: OkHostnameVerifier.java    From reader with MIT License 5 votes vote down vote up
private List<String> getSubjectAltNames(X509Certificate certificate, int type) {
  List<String> result = new ArrayList<String>();
  try {
    Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames();
    if (subjectAltNames == null) {
      return Collections.emptyList();
    }
    for (Object subjectAltName : subjectAltNames) {
      List<?> entry = (List<?>) subjectAltName;
      if (entry == null || entry.size() < 2) {
        continue;
      }
      Integer altNameType = (Integer) entry.get(0);
      if (altNameType == null) {
        continue;
      }
      if (altNameType == type) {
        String altName = (String) entry.get(1);
        if (altName != null) {
          result.add(altName);
        }
      }
    }
    return result;
  } catch (CertificateParsingException e) {
    return Collections.emptyList();
  }
}
 
Example #22
Source File: Asn1Utils.java    From AttestationServer with MIT License 5 votes vote down vote up
private static long bigIntegerToLong(BigInteger bigInt) throws CertificateParsingException {
    if (bigInt.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0
            || bigInt.compareTo(BigInteger.ZERO) < 0) {
        throw new CertificateParsingException("INTEGER out of bounds");
    }
    return bigInt.longValue();
}
 
Example #23
Source File: X509ExtensionUtil.java    From ripple-lib-java with ISC License 5 votes vote down vote up
public static Collection getSubjectAlternativeNames(X509Certificate cert)
        throws CertificateParsingException
{        
    byte[] extVal = cert.getExtensionValue(X509Extension.subjectAlternativeName.getId());

    return getAlternativeNames(extVal);
}
 
Example #24
Source File: SetupOteCommandTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailure_invalidCert() {
  CertificateParsingException thrown =
      assertThrows(
          CertificateParsingException.class,
          () ->
              runCommandForced(
                  "--ip_allow_list=1.1.1.1",
                  "--registrar=blobio",
                  "[email protected]",
                  "--certfile=/dev/null"));
  assertThat(thrown).hasMessageThat().contains("No X509Certificate found");
}
 
Example #25
Source File: OkHostnameVerifier.java    From styT with Apache License 2.0 5 votes vote down vote up
private static List<String> getSubjectAltNames(X509Certificate certificate, int type) {
  List<String> result = new ArrayList<>();
  try {
    Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames();
    if (subjectAltNames == null) {
      return Collections.emptyList();
    }
    for (Object subjectAltName : subjectAltNames) {
      List<?> entry = (List<?>) subjectAltName;
      if (entry == null || entry.size() < 2) {
        continue;
      }
      Integer altNameType = (Integer) entry.get(0);
      if (altNameType == null) {
        continue;
      }
      if (altNameType == type) {
        String altName = (String) entry.get(1);
        if (altName != null) {
          result.add(altName);
        }
      }
    }
    return result;
  } catch (CertificateParsingException e) {
    return Collections.emptyList();
  }
}
 
Example #26
Source File: TPMAttestationStatementValidator.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
private void validateSubjectAlternativeName(X509Certificate certificate) throws CertificateParsingException {
    try {
        for (List<?> entry : certificate.getSubjectAlternativeNames()) {
            if (entry.get(0).equals(4)) {
                X500Name directoryName = new X500Name((String) entry.get(1));
                TPMDeviceProperty tpmDeviceProperty = parseTPMDeviceProperty(directoryName);
                tpmDevicePropertyValidator.validate(tpmDeviceProperty);
                return;
            }
        }
    } catch (IOException | RuntimeException e) {
        throw new BadAttestationStatementException("The Subject Alternative Name extension of attestation certificate does not contain a TPM device property", e);
    }
    throw new BadAttestationStatementException("The Subject Alternative Name extension of attestation certificate does not contain a TPM device property");
}
 
Example #27
Source File: IdentityStore.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Certificate Signing Request based on the private key and certificate identified by the provided alias.
 *
 * When the alias does not identify a private key and/or certificate, this method will throw an exception.
 *
 * The certificate that is identified by the provided alias can be an unsigned certificate, but also a certificate
 * that is already signed. The latter implies that the generated request is a request for certificate renewal.
 *
 * An invocation of this method does not change the state of the underlying store.
 *
 * @param alias An identifier for a private key / certificate in this store (cannot be null).
 * @return A PEM-encoded Certificate Signing Request (never null).
 * @throws CertificateStoreConfigException if there was a problem generating the CSR
 */
public String generateCSR( String alias ) throws CertificateStoreConfigException
{
    // Input validation
    if ( alias == null || alias.trim().isEmpty() )
    {
        throw new IllegalArgumentException( "Argument 'alias' cannot be null or an empty String." );
    }
    alias = alias.trim();

    try
    {
        if ( !store.containsAlias( alias ) ) {
            throw new CertificateStoreConfigException( "Cannot generate CSR for alias '"+ alias +"': the alias does not exist in the store." );
        }

        final Certificate certificate = store.getCertificate( alias );
        if ( certificate == null || (!(certificate instanceof X509Certificate)))
        {
            throw new CertificateStoreConfigException( "Cannot generate CSR for alias '"+ alias +"': there is no corresponding certificate in the store, or it is not an X509 certificate." );
        }

        final Key key = store.getKey( alias, configuration.getPassword() );
        if ( key == null || (!(key instanceof PrivateKey) ) )
        {
            throw new CertificateStoreConfigException( "Cannot generate CSR for alias '"+ alias +"': there is no corresponding key in the store, or it is not a private key." );
        }

        final String pemCSR = CertificateManager.createSigningRequest( (X509Certificate) certificate, (PrivateKey) key );

        return pemCSR;
    }
    catch ( IOException | KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException | OperatorCreationException | CertificateParsingException e )
    {
        throw new CertificateStoreConfigException( "Cannot generate CSR for alias '"+ alias +"'", e );
    }
}
 
Example #28
Source File: Alexa.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
private boolean checkCertSubjectAlternativeName(X509Certificate cert) {
	Collection<List<?>> san;
	try {
		san = cert.getSubjectAlternativeNames();
		for (List<?> s : san) {
			for(Object q : s) {
				if(q.equals("echo-api.amazon.com")) { return true; }
			}
		}
	} catch (CertificateParsingException e) {
		e.printStackTrace();
	}
	return false;
}
 
Example #29
Source File: CertificateParsingExceptionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test for <code>CertificateParsingException(Throwable)</code>
 * constructor Assertion: constructs CertificateParsingException when
 * <code>cause</code> is not null
 */
public void testCertificateParsingException05() {
    CertificateParsingException tE = new CertificateParsingException(tCause);
    if (tE.getMessage() != null) {
        String toS = tCause.toString();
        String getM = tE.getMessage();
        assertTrue("getMessage() should contain ".concat(toS), (getM
                .indexOf(toS) != -1));
    }
    assertNotNull("getCause() must not return null", tE.getCause());
    assertEquals("getCause() must return ".concat(tCause.toString()), tE
            .getCause(), tCause);
}
 
Example #30
Source File: WaveSignatureVerifier.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the authority given matches any of the
 * SubjectAlternativeNames present in the certificate, false otherwise.
 */
private boolean authorityMatchesSubjectAlternativeNames(String authority,
    X509Certificate certificate) {

  Collection<List<?>> subjAltNames = null;
  try {
    subjAltNames = certificate.getSubjectAlternativeNames();
  } catch (CertificateParsingException e) {

    // This is a bit strange - it means that the AubjectAlternativeNames
    // extension wasn't properly encoded in this cert. We'll leave subjAltNames null.
  }

  if (subjAltNames == null) {
    return false;
  }

  for (List<?> altName : subjAltNames) {

    Integer nameType = (Integer) altName.get(0);

    // We're only interested in alternative names that denote domain names.
    if (!ALT_NAME_TYPE_DNS.equals(nameType)) {
      continue;
    }

    String dnsName = (String) altName.get(1);
    if (authority.equals(dnsName)) {
      return true;
    }
  }

  // None of the names matched.
  return false;
}