Search in sources :

Example 1 with UnsupportedFormatException

use of org.cloudfoundry.credhub.util.PrivateKeyReader.UnsupportedFormatException in project credhub by cloudfoundry-incubator.

the class CertificateMatchesPrivateKeyValidator method isValid.

@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    try {
        Field certificateField = value.getClass().getDeclaredField("certificate");
        Field privateKeyField = value.getClass().getDeclaredField("privateKey");
        certificateField.setAccessible(true);
        privateKeyField.setAccessible(true);
        final String certificateValue = (String) certificateField.get(value);
        final String privateKeyValue = (String) privateKeyField.get(value);
        if (StringUtils.isEmpty(certificateValue) || StringUtils.isEmpty(privateKeyValue)) {
            return true;
        }
        CertificateReader reader = new CertificateReader(certificateValue);
        if (!reader.isValid()) {
            return true;
        }
        final X509Certificate certificate = CertificateReader.getCertificate(certificateValue);
        final PublicKey certificatePublicKey = certificate.getPublicKey();
        final PublicKey publicKey = PrivateKeyReader.getPublicKey(privateKeyValue);
        return publicKey.equals(certificatePublicKey);
    } catch (UnsupportedFormatException e) {
        throw new ParameterizedValidationException("error.invalid_key_format", e.getMessage());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : Field(java.lang.reflect.Field) UnsupportedFormatException(org.cloudfoundry.credhub.util.PrivateKeyReader.UnsupportedFormatException) PublicKey(java.security.PublicKey) ParameterizedValidationException(org.cloudfoundry.credhub.exceptions.ParameterizedValidationException) X509Certificate(java.security.cert.X509Certificate) ParameterizedValidationException(org.cloudfoundry.credhub.exceptions.ParameterizedValidationException) UnsupportedFormatException(org.cloudfoundry.credhub.util.PrivateKeyReader.UnsupportedFormatException) CertificateReader(org.cloudfoundry.credhub.util.CertificateReader)

Aggregations

Field (java.lang.reflect.Field)1 PublicKey (java.security.PublicKey)1 X509Certificate (java.security.cert.X509Certificate)1 ParameterizedValidationException (org.cloudfoundry.credhub.exceptions.ParameterizedValidationException)1 CertificateReader (org.cloudfoundry.credhub.util.CertificateReader)1 UnsupportedFormatException (org.cloudfoundry.credhub.util.PrivateKeyReader.UnsupportedFormatException)1