Sample code for 30+ languages & platforms
Java

Duplicate PHP's openssl_encrypt and openssl_random_pseudo_bytes

See more OpenSSL Examples

Demonstrates how to duplicate PHP's openssl_encrypt function. (https://www.php.net/manual/en/function.openssl-encrypt.php)

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.Crypt2;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        // Duplicates thw following PHP script:

        // $text = "This is a test";
        // $passphrase = "my password";
        // $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length("AES-256-CBC"));
        // $crypted = base64_encode($iv.openssl_encrypt($text, "AES-256-CBC", $passphrase, OPENSSL_RAW_DATA, $iv));
        // echo $crypted;

        Crypt2 crypt = new Crypt2();

        String text = "This is a test";
        String passphrase = "my password";

        // AES is a block cipher.  The IV size for any block cipher is the size of the block, which is defined by the encryption algorithm.
        // For AES, the block size is always 16 bytes, regardless of key size (i.e. 128-bits, 192-bits, or 256-bits).
        // Therefore, generate 16 random bytes for the IV.
        crypt.setEncodingMode("base64");
        String ivBase64 = crypt.genRandomBytesENC(16);

        System.out.println("Generated IV = " + ivBase64);

        // Because we're doing AES-256-CBC, the key length must be 256-bits (i.e. 32 bytes).
        // Given that our passphrase is a us-ascii string that can be shorter or longer than 32-bytes, we need to
        // somehow transform the passphrase to a 32-byte secret key.  We need to know what openssl_encrypt does.
        // Here's the answer from the openssl_encrypt documentation:
        //
        // "If the passphrase is shorter than expected, it is silently padded with NUL characters;
        // if the passphrase is longer than expected, it is silently truncated."

        // OK.... so let's pad or shorten to get a 32-byte key.
        BinData bdKey = new BinData();
        bdKey.appendString(passphrase, "utf-8");

        int sz = bdKey.getNumBytes();
        if (sz > 32) {
            bdKey.removeChunk(32, sz - 32);
        } else {
            bdKey.clear();
            bdKey.appendPadded(passphrase, "utf-8", false, 32);
        }

        // Setup for encryption.
        crypt.setCryptAlgorithm("aes");
        crypt.setKeyLength(256);
        crypt.setEncodedIV(ivBase64, "base64");
        crypt.setEncodedKey(bdKey.getEncoded("base64"), "base64");

        // Encrypt and base64 encode.
        String cipherText64 = crypt.encryptStringENC(text);

        // The PHP code fragment above returns the base64 encoded bytes of the IV and the encrypted text.
        // So let's do that..
        BinData bd = new BinData();
        bd.appendEncoded(ivBase64, "base64");
        bd.appendEncoded(cipherText64, "base64");
        String result = bd.getEncoded("base64");

        System.out.println("result = " + result);

        // Sample output:
        // dN0vS1O0cWi5BbLAAY+NTf7bs3S27xzPf11RkG47sjs=

        // Now let's decrypt from the output...

        // Setup for decryption.
        crypt.setCryptAlgorithm("aes");
        crypt.setKeyLength(256);
        crypt.setEncodedKey(bdKey.getEncoded("base64"), "base64");

        BinData bdResult = new BinData();
        bdResult.appendEncoded(result, "base64");
        crypt.setEncodedIV(bdResult.getEncodedChunk(0, 16, "base64"), "base64");

        // Remove the IV (first 16 bytes) from the result.
        bdResult.removeChunk(0, 16);
        crypt.decryptBd(bdResult);
        String originalText = bdResult.getString("utf-8");

        System.out.println("original text = " + originalText);
    }
}