Search in sources :

Example 1 with Certificate

use of org.wso2.carbon.identity.api.server.idp.v1.model.Certificate in project carbon-apimgt by wso2.

the class Util method getAuthHeader.

public static String getAuthHeader(String username) throws Exception {
    // Get the filesystem key store default primary certificate
    KeyStoreManager keyStoreManager;
    keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
    try {
        keyStoreManager.getDefaultPrimaryCertificate();
        JWSSigner signer = new RSASSASigner((RSAPrivateKey) keyStoreManager.getDefaultPrivateKey());
        JWTClaimsSet.Builder jwtClaimsSetBuilder = new JWTClaimsSet.Builder();
        jwtClaimsSetBuilder.claim("Username", username);
        SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS512), jwtClaimsSetBuilder.build());
        signedJWT.sign(signer);
        // generate authorization header value
        return "Bearer " + Base64Utils.encode(signedJWT.serialize().getBytes(Charset.defaultCharset()));
    } catch (SignatureException e) {
        String msg = "Failed to sign with signature instance";
        log.error(msg, e);
        throw new Exception(msg, e);
    } catch (Exception e) {
        String msg = "Failed to get primary default certificate";
        log.error(msg, e);
        throw new Exception(msg, e);
    }
}
Also used : KeyStoreManager(org.wso2.carbon.core.util.KeyStoreManager) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) SignedJWT(com.nimbusds.jwt.SignedJWT) SignatureException(java.security.SignatureException) JWSSigner(com.nimbusds.jose.JWSSigner) JWSHeader(com.nimbusds.jose.JWSHeader) SignatureException(java.security.SignatureException)

Example 2 with Certificate

use of org.wso2.carbon.identity.api.server.idp.v1.model.Certificate in project carbon-apimgt by wso2.

the class APIUtil method verifyTokenSignature.

/**
 * Verify the JWT token signature.
 * <p>
 * This method only used for API Key revocation which contains some duplicate logic in GatewayUtils class.
 *
 * @param splitToken The JWT token which is split into [header, payload, signature]
 * @return whether the signature is verified or or not
 */
public static boolean verifyTokenSignature(String[] splitToken, Certificate certificate, String signatureAlgorithm) throws APIManagementException {
    // Retrieve public key from the certificate
    PublicKey publicKey = certificate.getPublicKey();
    try {
        // Verify token signature
        Signature signatureInstance = Signature.getInstance(signatureAlgorithm);
        signatureInstance.initVerify(publicKey);
        String assertion = splitToken[0] + "." + splitToken[1];
        signatureInstance.update(assertion.getBytes());
        byte[] decodedSignature = java.util.Base64.getUrlDecoder().decode(splitToken[2]);
        return signatureInstance.verify(decodedSignature);
    } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | IllegalArgumentException e) {
        String msg = "Error while verifying JWT signature with signature algorithm " + signatureAlgorithm;
        log.error(msg, e);
        throw new APIManagementException(msg, e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublicKey(java.security.PublicKey) Signature(java.security.Signature) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException)

Example 3 with Certificate

use of org.wso2.carbon.identity.api.server.idp.v1.model.Certificate in project carbon-apimgt by wso2.

the class CertificateMgtUtils method validateCertificate.

/**
 * To validate the current certificate and alias.
 *
 * @param alias       Alias of the certificate.
 * @param certificate Bas64 endcoded certificated.
 * @return response code based on the validation
 */
public ResponseCode validateCertificate(String alias, int tenantId, String certificate) {
    File trustStoreFile = new File(trustStoreLocation);
    ResponseCode responseCode = ResponseCode.SUCCESS;
    ByteArrayInputStream serverCert = null;
    try {
        synchronized (this) {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            try (InputStream localTrustStoreStream = new FileInputStream(trustStoreFile)) {
                trustStore.load(localTrustStoreStream, trustStorePassword);
            }
            if (StringUtils.isNotEmpty(alias) && trustStore.containsAlias(alias + "_" + tenantId)) {
                responseCode = ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE;
            }
        }
        if (responseCode != ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE) {
            byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8)));
            serverCert = new ByteArrayInputStream(cert);
            if (serverCert.available() == 0) {
                responseCode = ResponseCode.CERTIFICATE_NOT_FOUND;
            } else {
                CertificateFactory cf = CertificateFactory.getInstance(certificateType);
                while (serverCert.available() > 0) {
                    Certificate generatedCertificate = cf.generateCertificate(serverCert);
                    X509Certificate x509Certificate = (X509Certificate) generatedCertificate;
                    if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) {
                        responseCode = ResponseCode.CERTIFICATE_EXPIRED;
                    }
                }
            }
        }
    } catch (IOException e) {
        log.error("I/O Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (CertificateException e) {
        log.error("Certificate Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (NoSuchAlgorithmException e) {
        log.error("No Such Algorithm Exception while trying to load trust store while trying to check whether " + "alias " + alias + " exists", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (KeyStoreException e) {
        log.error("KeyStore Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } finally {
        closeStreams(serverCert);
    }
    return responseCode;
}
Also used : ResponseCode(org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) File(java.io.File) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 4 with Certificate

use of org.wso2.carbon.identity.api.server.idp.v1.model.Certificate in project carbon-apimgt by wso2.

the class CertificateMgtUtils method updateCertificate.

/**
 * Method to update the certificate which matches the given alias.
 *
 * @param certificate: The base64 encoded certificate string.
 * @param alias        : Alias of the certificate that should be retrieved.
 * @return :
 */
public synchronized ResponseCode updateCertificate(String certificate, String alias) throws CertificateManagementException {
    try {
        File trustStoreFile = new File(trustStoreLocation);
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream localTrustStoreStream = new FileInputStream(trustStoreFile)) {
            trustStore.load(localTrustStoreStream, trustStorePassword);
        }
        if (trustStore.getCertificate(alias) == null) {
            log.error("Could not update the certificate. The certificate for alias '" + alias + "' is not found" + " in the trust store.");
            return ResponseCode.CERTIFICATE_NOT_FOUND;
        }
        // Generate the certificate from the input string.
        byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8)));
        Certificate newCertificate;
        try (InputStream certificateStream = new ByteArrayInputStream(cert)) {
            if (certificateStream.available() == 0) {
                log.error("Certificate is empty for the provided alias " + alias);
                return ResponseCode.INTERNAL_SERVER_ERROR;
            }
            CertificateFactory certificateFactory = CertificateFactory.getInstance(certificateType);
            newCertificate = certificateFactory.generateCertificate(certificateStream);
        }
        X509Certificate x509Certificate = (X509Certificate) newCertificate;
        if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) {
            log.error("Could not update the certificate. The certificate expired.");
            return ResponseCode.CERTIFICATE_EXPIRED;
        }
        // If the certificate is not expired, delete the existing certificate and add the new cert.
        trustStore.deleteEntry(alias);
        // Store the certificate in the trust store.
        trustStore.setCertificateEntry(alias, newCertificate);
        try (OutputStream fileOutputStream = new FileOutputStream(trustStoreFile)) {
            trustStore.store(fileOutputStream, trustStorePassword);
        }
    } catch (IOException e) {
        throw new CertificateManagementException("Error updating certificate.", e);
    } catch (CertificateException e) {
        throw new CertificateManagementException("Error generating the certificate.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateManagementException("Error loading the keystore.", e);
    } catch (KeyStoreException e) {
        throw new CertificateManagementException("Error updating the certificate in the keystore.", e);
    }
    return ResponseCode.SUCCESS;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) CertificateManagementException(org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateManagementException) File(java.io.File) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 5 with Certificate

use of org.wso2.carbon.identity.api.server.idp.v1.model.Certificate in project carbon-apimgt by wso2.

the class CertificateMgtUtils method getCertificateContent.

/**
 * Retrieve the certificate which is represented by the given alias.
 *
 * @param alias : The alias of the required certificate.
 * @return : The Certificate as a ByteArrayInputStream.
 * @throws CertificateManagementException :
 */
public synchronized ByteArrayInputStream getCertificateContent(String alias) throws CertificateManagementException {
    File trustStoreFile = new File(trustStoreLocation);
    Certificate certificate;
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream localTrustStoreStream = new FileInputStream(trustStoreFile)) {
            trustStore.load(localTrustStoreStream, trustStorePassword);
        }
        if (trustStore.containsAlias(alias)) {
            certificate = trustStore.getCertificate(alias);
            return new ByteArrayInputStream(certificate.getEncoded());
        }
    } catch (IOException e) {
        throw new CertificateManagementException("Error in loading the certificate.", e);
    } catch (CertificateException e) {
        throw new CertificateManagementException("Error loading certificate.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateManagementException("Could not find the algorithm to load the certificate.", e);
    } catch (KeyStoreException e) {
        throw new CertificateManagementException("Error reading certificate contents.", e);
    }
    return null;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) CertificateManagementException(org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateManagementException) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) File(java.io.File) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

IOException (java.io.IOException)43 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)43 X509Certificate (java.security.cert.X509Certificate)29 CertificateException (java.security.cert.CertificateException)26 Certificate (java.security.cert.Certificate)25 KeyStore (java.security.KeyStore)22 ArrayList (java.util.ArrayList)22 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)20 KeyStoreException (java.security.KeyStoreException)19 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)17 ByteArrayInputStream (java.io.ByteArrayInputStream)16 PreparedStatement (java.sql.PreparedStatement)16 SQLException (java.sql.SQLException)16 FileInputStream (java.io.FileInputStream)14 KeyStoreManager (org.wso2.carbon.core.util.KeyStoreManager)14 ClientCertificateDTO (org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO)13 InputStream (java.io.InputStream)12 Connection (java.sql.Connection)12 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)12 UserStoreException (org.wso2.carbon.user.api.UserStoreException)12