Ruby Encryption Sample Code
require 'openssl'
require 'base64'
def hex_to_bytes(hex)
[hex].pack('H*')
end
def bytes_to_hex(bytes)
bytes.unpack('H*').first
end
# Encrypt function
def encrypt(data, key_hex, iv_hex)
key = hex_to_bytes(key_hex)
iv = hex_to_bytes(iv_hex)
cipher = OpenSSL::Cipher.new('AES-256-CBC')
cipher.encrypt
cipher.key = key
cipher.iv = iv
encrypted = cipher.update(data) + cipher.final
bytes_to_hex(encrypted)
end
# Decrypt function
def decrypt(encrypted_hex, key_hex, iv_hex)
key = hex_to_bytes(key_hex)
iv = hex_to_bytes(iv_hex)
encrypted = hex_to_bytes(encrypted_hex)
cipher = OpenSSL::Cipher.new('AES-256-CBC')
cipher.decrypt
cipher.key = key
cipher.iv = iv
decrypted = cipher.update(encrypted) + cipher.final
decrypted
end
# Example usage
key_hex = "97b7a43a0e70b4e73a157670151671903ebc1ec1843e78a06ea6e0f85d60048d" # 32 bytes
iv_hex = "db3777f596e190fadb3777f596e190fa" # 16 bytes
plaintext = '{ "p1":"212201508185", "p2":"ICIC0002122", "p3":"UB456787654", "p4":"61a", "p5":"DEV", "p6":"9090686809", "p7":"dev.pandey@nerasoft.in", "p8":"ravi", "p9":"vendor payment", "p10":"27.1111,54.1111" }'
enctext = '150aebe6a7c4b55c064ebe17e7a096b2be6ca6e9394c165bbe0efd882c5b4ae93e7f895e0223f0151811bc55c000d37c63596964cfd576783307411d7522a0c9fed19e6d2ab16151e124ba248395932d3bd6328229f16ba96623292f670b73c4c0c704689bc7306714a77d3d4d14e74a63566f67604f019cacf0fd031ef7337a874e8132e4dab1a3a24cdcc38fad80f0812c3fc146bef7cc3f43eb7e1c632372ab710f4c68ba0b762dd71fb5828ed76bd25025ba48649644b9bf9e555f656c09
'
# Encrypt
encrypted_hex = encrypt(plaintext, key_hex, iv_hex)
puts "Encrypted (Hex): #{encrypted_hex}"
# Decrypt
decrypted_text = decrypt(enctext, key_hex, iv_hex)
puts "Decrypted Text: #{decrypted_text}"
Platforms Supported:
.NET (C#): This example uses System.Security.Cryptography for AES encryption and decryption.
Java: Uses javax.crypto for AES encryption and decryption.
Ruby: Uses the openssl library for AES encryption and decryption.
Python: Uses pycryptodome for AES encryption and decryption.
PHP: Uses openssl_encrypt and openssl_decrypt.
General Key and IV:
For all these examples, the key must be 32 bytes long, and the IV must be 16 bytes long for AES-256-CBC.
Make sure to replace the key and IV with actual values you intend to use for encryption and decryption across all platforms.