Search in sources :

Example 1 with EciesDecryptor

use of io.getlime.security.powerauth.crypto.lib.encryptor.ecies.EciesDecryptor in project powerauth-restful-integration by lime-company.

the class PowerAuthEncryptionProviderBase method decryptRequest.

/**
 * Decrypt HTTP request body and construct object with ECIES data. Use the requestType parameter to specify
 * the type of decrypted object.
 *
 * @param request HTTP request.
 * @param requestType Class of request object.
 * @param eciesScope ECIES scope.
 * @return Object with ECIES data.
 * @throws PowerAuthEncryptionException In case request decryption fails.
 */
@Nonnull
public PowerAuthEciesEncryption decryptRequest(@Nonnull HttpServletRequest request, @Nonnull Type requestType, @Nonnull EciesScope eciesScope) throws PowerAuthEncryptionException {
    // Only POST HTTP method is supported for ECIES
    if (!"POST".equals(request.getMethod())) {
        logger.warn("Invalid HTTP method: {}", request.getMethod());
        throw new PowerAuthEncryptionException();
    }
    // Resolve either signature or encryption HTTP header for ECIES
    final EciesEncryptionContext encryptionContext = extractEciesEncryptionContext(request);
    // Construct ECIES encryption object from HTTP header
    final PowerAuthEciesEncryption eciesEncryption = new PowerAuthEciesEncryption(encryptionContext);
    // Save ECIES scope in context
    eciesEncryption.getContext().setEciesScope(eciesScope);
    try {
        // Parse ECIES cryptogram from request body
        final PowerAuthRequestBody requestBody = ((PowerAuthRequestBody) request.getAttribute(PowerAuthRequestObjects.REQUEST_BODY));
        if (requestBody == null) {
            logger.warn("The X-PowerAuth-Request-Body request attribute is missing. Register the PowerAuthRequestFilter to fix this error.");
            throw new PowerAuthEncryptionException();
        }
        final byte[] requestBodyBytes = requestBody.getRequestBytes();
        if (requestBodyBytes == null || requestBodyBytes.length == 0) {
            logger.warn("Invalid HTTP request");
            throw new PowerAuthEncryptionException();
        }
        final EciesEncryptedRequest eciesRequest = objectMapper.readValue(requestBodyBytes, EciesEncryptedRequest.class);
        if (eciesRequest == null) {
            logger.warn("Invalid ECIES request data");
            throw new PowerAuthEncryptionException();
        }
        // Prepare ephemeral public key
        final String ephemeralPublicKey = eciesRequest.getEphemeralPublicKey();
        final String encryptedData = eciesRequest.getEncryptedData();
        final String mac = eciesRequest.getMac();
        final String nonce = eciesRequest.getNonce();
        // Verify ECIES request data. Nonce is required for protocol 3.1+
        if (ephemeralPublicKey == null || encryptedData == null || mac == null) {
            logger.warn("Invalid ECIES request data");
            throw new PowerAuthEncryptionException();
        }
        if (nonce == null && !"3.0".equals(encryptionContext.getVersion())) {
            logger.warn("Missing nonce in ECIES request data");
            throw new PowerAuthEncryptionException();
        }
        final byte[] ephemeralPublicKeyBytes = BaseEncoding.base64().decode(ephemeralPublicKey);
        final byte[] encryptedDataBytes = BaseEncoding.base64().decode(encryptedData);
        final byte[] macBytes = BaseEncoding.base64().decode(mac);
        final byte[] nonceBytes = nonce != null ? BaseEncoding.base64().decode(nonce) : null;
        final String applicationKey = eciesEncryption.getContext().getApplicationKey();
        final PowerAuthEciesDecryptorParameters decryptorParameters;
        // Obtain ECIES decryptor parameters from PowerAuth server
        switch(eciesScope) {
            case ACTIVATION_SCOPE:
                final String activationId = eciesEncryption.getContext().getActivationId();
                if (activationId == null) {
                    logger.warn("Activation ID is required in ECIES activation scope");
                    throw new PowerAuthEncryptionException();
                }
                decryptorParameters = getEciesDecryptorParameters(activationId, applicationKey, ephemeralPublicKey);
                break;
            case APPLICATION_SCOPE:
                decryptorParameters = getEciesDecryptorParameters(null, applicationKey, ephemeralPublicKey);
                break;
            default:
                logger.warn("Unsupported ECIES scope: {}", eciesScope);
                throw new PowerAuthEncryptionException();
        }
        // Prepare envelope key and sharedInfo2 parameter for decryptor
        final byte[] secretKey = BaseEncoding.base64().decode(decryptorParameters.getSecretKey());
        final EciesEnvelopeKey envelopeKey = new EciesEnvelopeKey(secretKey, ephemeralPublicKeyBytes);
        final byte[] sharedInfo2 = BaseEncoding.base64().decode(decryptorParameters.getSharedInfo2());
        // Construct decryptor and set it to the request for later encryption of response
        final EciesDecryptor eciesDecryptor = eciesFactory.getEciesDecryptor(envelopeKey, sharedInfo2);
        eciesEncryption.setEciesDecryptor(eciesDecryptor);
        // Decrypt request data
        final EciesCryptogram cryptogram = new EciesCryptogram(ephemeralPublicKeyBytes, macBytes, encryptedDataBytes, nonceBytes);
        final byte[] decryptedData = eciesDecryptor.decryptRequest(cryptogram);
        eciesEncryption.setEncryptedRequest(encryptedDataBytes);
        eciesEncryption.setDecryptedRequest(decryptedData);
        // Set the request object only in case when request data is sent
        if (decryptedData.length != 0) {
            eciesEncryption.setRequestObject(deserializeRequestData(decryptedData, requestType));
        }
        // Set encryption object in HTTP servlet request
        request.setAttribute(PowerAuthRequestObjects.ENCRYPTION_OBJECT, eciesEncryption);
    } catch (Exception ex) {
        logger.debug("Request decryption failed, error: " + ex.getMessage(), ex);
        throw new PowerAuthEncryptionException();
    }
    return eciesEncryption;
}
Also used : EciesCryptogram(io.getlime.security.powerauth.crypto.lib.encryptor.ecies.model.EciesCryptogram) PowerAuthEciesEncryption(io.getlime.security.powerauth.rest.api.spring.encryption.PowerAuthEciesEncryption) PowerAuthEncryptionException(io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthEncryptionException) EciesEncryptedRequest(io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest) PowerAuthRequestBody(io.getlime.security.powerauth.rest.api.spring.model.PowerAuthRequestBody) EciesEnvelopeKey(io.getlime.security.powerauth.crypto.lib.encryptor.ecies.EciesEnvelopeKey) EciesDecryptor(io.getlime.security.powerauth.crypto.lib.encryptor.ecies.EciesDecryptor) PowerAuthEncryptionException(io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthEncryptionException) InvalidPowerAuthHttpHeaderException(io.getlime.security.powerauth.http.validator.InvalidPowerAuthHttpHeaderException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) EciesEncryptionContext(io.getlime.security.powerauth.rest.api.spring.encryption.EciesEncryptionContext) PowerAuthEciesDecryptorParameters(io.getlime.security.powerauth.rest.api.spring.encryption.PowerAuthEciesDecryptorParameters) Nonnull(javax.annotation.Nonnull)

Example 2 with EciesDecryptor

use of io.getlime.security.powerauth.crypto.lib.encryptor.ecies.EciesDecryptor in project powerauth-restful-integration by lime-company.

the class EncryptionResponseBodyAdvice method beforeBodyWrite.

/**
 * Encrypt response before writing body.
 *
 * @param response Response object.
 * @param methodParameter Method parameter.
 * @param mediaType Selected HTTP response media type.
 * @param converterClass Selected HTTP message converter class.
 * @param serverHttpRequest HTTP request.
 * @param serverHttpResponse HTTP response.
 * @return ECIES cryptogram.
 */
@Override
public Object beforeBodyWrite(Object response, @NonNull MethodParameter methodParameter, @NonNull MediaType mediaType, @NonNull Class<? extends HttpMessageConverter<?>> converterClass, @NonNull ServerHttpRequest serverHttpRequest, @NonNull ServerHttpResponse serverHttpResponse) {
    if (response == null) {
        return null;
    }
    // Extract ECIES encryption object from HTTP request
    final HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) serverHttpRequest).getServletRequest();
    final PowerAuthEciesEncryption eciesEncryption = (PowerAuthEciesEncryption) httpServletRequest.getAttribute(PowerAuthRequestObjects.ENCRYPTION_OBJECT);
    if (eciesEncryption == null) {
        return null;
    }
    // Convert response to JSON
    try {
        byte[] responseBytes = serializeResponseObject(response);
        // Encrypt response using decryptor and return ECIES cryptogram
        final EciesDecryptor eciesDecryptor = eciesEncryption.getEciesDecryptor();
        final EciesCryptogram cryptogram = eciesDecryptor.encryptResponse(responseBytes);
        final String encryptedDataBase64 = BaseEncoding.base64().encode(cryptogram.getEncryptedData());
        final String macBase64 = BaseEncoding.base64().encode(cryptogram.getMac());
        // Return encrypted response with type given by converter class
        final EciesEncryptedResponse encryptedResponse = new EciesEncryptedResponse(encryptedDataBase64, macBase64);
        if (converterClass.isAssignableFrom(MappingJackson2HttpMessageConverter.class)) {
            // Object conversion is done automatically using MappingJackson2HttpMessageConverter
            return encryptedResponse;
        } else if (converterClass.isAssignableFrom(StringHttpMessageConverter.class)) {
            // Conversion to byte[] is done using first applicable configured HTTP message converter, corresponding String is returned
            return new String(convertEncryptedResponse(encryptedResponse, mediaType), StandardCharsets.UTF_8);
        } else {
            // Conversion to byte[] is done using first applicable configured HTTP message converter
            return convertEncryptedResponse(encryptedResponse, mediaType);
        }
    } catch (Exception ex) {
        logger.warn("Encryption failed, error: {}", ex.getMessage());
        logger.debug("Error details", ex);
        return null;
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) EciesCryptogram(io.getlime.security.powerauth.crypto.lib.encryptor.ecies.model.EciesCryptogram) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) PowerAuthEciesEncryption(io.getlime.security.powerauth.rest.api.spring.encryption.PowerAuthEciesEncryption) EciesEncryptedResponse(io.getlime.security.powerauth.rest.api.model.response.v3.EciesEncryptedResponse) EciesDecryptor(io.getlime.security.powerauth.crypto.lib.encryptor.ecies.EciesDecryptor) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) IOException(java.io.IOException)

Aggregations

EciesDecryptor (io.getlime.security.powerauth.crypto.lib.encryptor.ecies.EciesDecryptor)2 EciesCryptogram (io.getlime.security.powerauth.crypto.lib.encryptor.ecies.model.EciesCryptogram)2 PowerAuthEciesEncryption (io.getlime.security.powerauth.rest.api.spring.encryption.PowerAuthEciesEncryption)2 IOException (java.io.IOException)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 EciesEnvelopeKey (io.getlime.security.powerauth.crypto.lib.encryptor.ecies.EciesEnvelopeKey)1 InvalidPowerAuthHttpHeaderException (io.getlime.security.powerauth.http.validator.InvalidPowerAuthHttpHeaderException)1 EciesEncryptedRequest (io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest)1 EciesEncryptedResponse (io.getlime.security.powerauth.rest.api.model.response.v3.EciesEncryptedResponse)1 EciesEncryptionContext (io.getlime.security.powerauth.rest.api.spring.encryption.EciesEncryptionContext)1 PowerAuthEciesDecryptorParameters (io.getlime.security.powerauth.rest.api.spring.encryption.PowerAuthEciesDecryptorParameters)1 PowerAuthEncryptionException (io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthEncryptionException)1 PowerAuthRequestBody (io.getlime.security.powerauth.rest.api.spring.model.PowerAuthRequestBody)1 Nonnull (javax.annotation.Nonnull)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 StringHttpMessageConverter (org.springframework.http.converter.StringHttpMessageConverter)1 ServletServerHttpRequest (org.springframework.http.server.ServletServerHttpRequest)1