News and Events

News and Events

Mule Secure Configuration Properties (Blowfish) Programmatically

Have you ever had a need to encrypt or decrypt data the same exact way as done by Mule 4 Secure Configuration Properties? Well, here is an example of accomplishing that with Blowfish + CBC(default) algorithm. This is a very convenient way to encrypt any sensitive data instead of masking it, especially since we already have mule key setup within Mule application.


%dw 2.0
output application/json
import java!com::netflexity::utils::BlowfishUtils
---
(payload - "ssn") ++ {
ssn: BlowfishUtils::decrypt(Mule::p("mule.key"), payload.ssn)
}

package com.netflexity.utils;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public final static String decrypt(String key, String encryptedData) {
 try {
     byte[] decoded = Base64.getDecoder().decode(encryptedData.getBytes("UTF-8"));
     byte[] keyBytes = key.getBytes("UTF-8");

    // Get Cipher.
    Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");

    // Use block size of the key as IV.
    byte[] iv = new byte[cipher.getBlockSize()];
    for (int i = 0; i < cipher.getBlockSize(); i++) {
        iv[i] = keyBytes[i];
    }
    IvParameterSpec ivSpec = new IvParameterSpec(iv);

    // Create secret key.
    SecretKey secretKey = new SecretKeySpec(keyBytes, "Blowfish");

    // Init Cipher in decrypt mode.
    cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);

    return new String(cipher.doFinal(decoded));
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}