Skip to content

Instantly share code, notes, and snippets.

@nahi
Created June 16, 2011 11:57
Show Gist options
  • Save nahi/1029091 to your computer and use it in GitHub Desktop.
Save nahi/1029091 to your computer and use it in GitHub Desktop.
AES-256-CBC encryption/decryption w/o using JCE on JRuby
# Java's JCE requires extra JVM config download named Jurisdiction Policy Files where AES keysize > 128bit.
# You can do encrypt/decrypt using BouncyCastle via JRuby's Java integration like this.
# Use this at your own risk.
require 'java'
require 'openssl'
java_import 'org.bouncycastle.crypto.BlockCipher'
java_import 'org.bouncycastle.crypto.engines.AESLightEngine'
java_import 'org.bouncycastle.crypto.modes.CBCBlockCipher'
java_import 'org.bouncycastle.crypto.params.KeyParameter'
java_import 'org.bouncycastle.crypto.params.ParametersWithIV'
bits = 256
message = "Hello World"
# encrypt w/o Jurisdiction policy files using BC.
cipher = CBCBlockCipher.new(AESLightEngine.new)
block_size = cipher.block_size
key = OpenSSL::Random.random_bytes(bits / 8)
iv = OpenSSL::Random.random_bytes(block_size)
param = ParametersWithIV.new(KeyParameter.new(key.to_java_bytes), iv.to_java_bytes)
cipher.init(true, param)
# bogus padding; do PKCS5 padding instead
len = message.bytesize
padded = (message + " " * (((len / block_size) + 1) * block_size - len)).to_java_bytes
buf = ("\0" * padded.length).to_java_bytes
0.upto(padded.length / block_size - 1) do |idx|
pos = idx * block_size
cipher.process_block(padded, pos, buf, pos)
end
cipher_text = String.from_java_bytes(buf)
# decrypt
cipher.init(false, param)
padded = cipher_text.to_java_bytes
buf = ("\0" * padded.length).to_java_bytes
0.upto(padded.length / block_size - 1) do |idx|
pos = idx * block_size
cipher.process_block(padded, pos, buf, pos)
end
plain_text_bc = String.from_java_bytes(buf)
p "decrypt by BC : " + plain_text_bc
# Following code needs Jurisdiction policy files.
cipher = OpenSSL::Cipher.new("AES-#{bits}-CBC")
cipher.decrypt
cipher.padding = 0
cipher.iv = iv
cipher.key = key
plain_text_jce = cipher.update(cipher_text) + cipher.final
p "decrypt by JCE: " + plain_text_jce
p plain_text_bc == plain_text_jce
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment