Skip to content

Instantly share code, notes, and snippets.

@heiswayi
Created November 17, 2023 17:33
Show Gist options
  • Save heiswayi/0e0faec0245f3492b33825c630d7ed9c to your computer and use it in GitHub Desktop.
Save heiswayi/0e0faec0245f3492b33825c630d7ed9c to your computer and use it in GitHub Desktop.
Encryption and Decryption in PHP, TypeScript, Ruby, C#, and Batch scripting

PHP + OpenSSL extension

<?php

function encryptData($data, $key, $iv) {
    $cipher = "aes-256-cbc";
    $options = 0;
    $encryptedData = openssl_encrypt($data, $cipher, $key, $options, $iv);
    return $encryptedData;
}

// Example usage:
$dataToEncrypt = "Hello, World!";
$key = openssl_random_pseudo_bytes(32); // 256-bit key
$iv = openssl_random_pseudo_bytes(16);  // 128-bit IV

$encryptedData = encryptData($dataToEncrypt, $key, $iv);

echo "Encrypted Data: " . base64_encode($encryptedData);
?>
<?php

function decryptData($encryptedData, $key, $iv) {
    $cipher = "aes-256-cbc";
    $options = 0;
    $decryptedData = openssl_decrypt(base64_decode($encryptedData), $cipher, $key, $options, $iv);
    return $decryptedData;
}

// Example usage:
$encryptedData = "encrypted-data-here";
$key = /* Same key used for encryption */;
$iv = /* Same IV used for encryption */;

$decryptedData = decryptData($encryptedData, $key, $iv);

echo "Decrypted Data: " . $decryptedData;
?>

TypeScript + crypto module

npm install @types/node
import * as crypto from 'crypto';

function encryptData(data: string, key: Buffer, iv: Buffer): string {
    const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
    let encryptedData = cipher.update(data, 'utf-8', 'base64');
    encryptedData += cipher.final('base64');
    return encryptedData;
}

// Example usage:
const dataToEncrypt = 'Hello, World!';
const key = crypto.randomBytes(32); // 256-bit key
const iv = crypto.randomBytes(16);  // 128-bit IV

const encryptedData = encryptData(dataToEncrypt, key, iv);

console.log('Encrypted Data:', encryptedData);
import * as crypto from 'crypto';

function decryptData(encryptedData: string, key: Buffer, iv: Buffer): string {
    const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    let decryptedData = decipher.update(encryptedData, 'base64', 'utf-8');
    decryptedData += decipher.final('utf-8');
    return decryptedData;
}

// Example usage:
const encryptedData = 'encrypted-data-here';
// Use the same key and IV used for encryption
const key = /* Same key used for encryption */;
const iv = /* Same IV used for encryption */;

const decryptedData = decryptData(encryptedData, key, iv);

console.log('Decrypted Data:', decryptedData);

C#

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static void Main()
    {
        string dataToEncrypt = "Hello, World!";
        byte[] key = GenerateRandomKey(32); // 256-bit key
        byte[] iv = GenerateRandomKey(16);  // 128-bit IV

        string encryptedData = EncryptData(dataToEncrypt, key, iv);

        Console.WriteLine("Encrypted Data: " + encryptedData);
    }

    static byte[] GenerateRandomKey(int size)
    {
        using (var rng = new RNGCryptoServiceProvider())
        {
            byte[] key = new byte[size];
            rng.GetBytes(key);
            return key;
        }
    }

    static string EncryptData(string data, byte[] key, byte[] iv)
    {
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = key;
            aesAlg.IV = iv;

            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(data);
                    }
                }
                return Convert.ToBase64String(msEncrypt.ToArray());
            }
        }
    }
}
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static void Main()
    {
        string encryptedData = "encrypted-data-here";
        byte[] key = /* Same key used for encryption */;
        byte[] iv = /* Same IV used for encryption */;

        string decryptedData = DecryptData(encryptedData, key, iv);

        Console.WriteLine("Decrypted Data: " + decryptedData);
    }

    static string DecryptData(string encryptedData, byte[] key, byte[] iv)
    {
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = key;
            aesAlg.IV = iv;

            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encryptedData)))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        return srDecrypt.ReadToEnd();
                    }
                }
            }
        }
    }
}

Python + cryptography library

pip install cryptography

encryption

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from base64 import b64encode
import os

def encrypt_data(data, key, iv):
    cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
    encryptor = cipher.encryptor()
    padder = padding.PKCS7(algorithms.AES.block_size).padder()
    data_padded = padder.update(data.encode('utf-8')) + padder.finalize()
    ciphertext = encryptor.update(data_padded) + encryptor.finalize()
    return b64encode(ciphertext).decode('utf-8')

# Example usage:
data_to_encrypt = "Hello, World!"
key = os.urandom(32)  # 256-bit key
iv = os.urandom(16)   # 128-bit IV

encrypted_data = encrypt_data(data_to_encrypt, key, iv)

print("Encrypted Data:", encrypted_data)
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from base64 import b64decode

def decrypt_data(encrypted_data, key, iv):
    cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
    decryptor = cipher.decryptor()
    ciphertext = b64decode(encrypted_data)
    decrypted_data_padded = decryptor.update(ciphertext) + decryptor.finalize()
    unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
    decrypted_data = unpadder.update(decrypted_data_padded) + unpadder.finalize()
    return decrypted_data.decode('utf-8')

# Example usage:
encrypted_data = "encrypted-data-here"
# Use the same key and IV used for encryption
key = /* Same key used for encryption */
iv = /* Same IV used for encryption */

decrypted_data = decrypt_data(encrypted_data, key, iv)

print("Decrypted Data:", decrypted_data)

Ruby + OpenSSL library

require 'openssl'
require 'base64'

def encrypt_data(data, key, iv)
  cipher = OpenSSL::Cipher.new('AES-256-CBC')
  cipher.encrypt
  cipher.key = key
  cipher.iv = iv
  encrypted_data = cipher.update(data) + cipher.final
  return Base64.strict_encode64(encrypted_data)
end

# Example usage:
data_to_encrypt = 'Hello, World!'
key = OpenSSL::Random.random_bytes(32) # 256-bit key
iv = OpenSSL::Random.random_bytes(16)  # 128-bit IV

encrypted_data = encrypt_data(data_to_encrypt, key, iv)

puts "Encrypted Data: #{encrypted_data}"
require 'openssl'
require 'base64'

def decrypt_data(encrypted_data, key, iv)
  cipher = OpenSSL::Cipher.new('AES-256-CBC')
  cipher.decrypt
  cipher.key = key
  cipher.iv = iv
  decrypted_data = cipher.update(Base64.strict_decode64(encrypted_data)) + cipher.final
  return decrypted_data
end

# Example usage:
encrypted_data = 'encrypted-data-here'
# Use the same key and IV used for encryption
key = # Same key used for encryption
iv = # Same IV used for encryption

decrypted_data = decrypt_data(encrypted_data, key, iv)

puts "Decrypted Data: #{decrypted_data}"

Windows Batch programming + OpenSSL tool

@echo off
setlocal enabledelayedexpansion

set "dataToEncrypt=Hello, World!"
set "keyFile=key.bin"
set "ivFile=iv.bin"
set "plaintextFile=plaintext.txt"
set "encryptedFile=encrypted.enc"

rem Generate a random key and IV
openssl rand -out !keyFile! 32
openssl rand -out !ivFile! 16

rem Save the data to a plaintext file
echo !dataToEncrypt! > !plaintextFile!

rem Encrypt the data using OpenSSL
openssl enc -aes-256-cbc -e -in !plaintextFile! -out !encryptedFile! -K !keyFile! -iv !ivFile!

echo Encrypted Data: !encryptedFile!

endlocal
@echo off
setlocal enabledelayedexpansion

set "keyFile=key.bin"
set "ivFile=iv.bin"
set "encryptedFile=encrypted.enc"
set "decryptedFile=decrypted.txt"

rem Decrypt the data using OpenSSL
openssl enc -aes-256-cbc -d -in !encryptedFile! -out !decryptedFile! -K !keyFile! -iv !ivFile!

rem Read and display the decrypted data
set /p decryptedData=< !decryptedFile!
echo Decrypted Data: !decryptedData!

endlocal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment