Skip to content

Instantly share code, notes, and snippets.

@mardambey
Created April 15, 2013 00:19
Show Gist options
  • Save mardambey/5384837 to your computer and use it in GitHub Desktop.
Save mardambey/5384837 to your computer and use it in GitHub Desktop.
AES/PKCS5 - encrypted with Perl::CBC and decrypted in Scala/Java
#!/usr/bin/perl -w
use strict;
use warnings;
use Crypt::CBC;
use MIME::Base64;
use Digest::MD5 qw(md5_hex);
my $plainText = "secret stuff goes here...";
my $id = "aabb-1234";
my $iv = substr(md5_hex($id), 0, 16);
my $cipher = Crypt::CBC->new(
-key => 'd2cb415e067c7b13',
-iv => $iv,
-cipher => 'OpenSSL::AES',
-literal_key => 1,
-header => "none",
-padding => "standard",
-keysize => 16
);
my $encrypted = $cipher->encrypt($plainText);
my $base64 = encode_base64($encrypted);
print("Ciphertext(b64):$base64\n");
import javax.crypto.spec.SecretKeySpec
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import java.math.BigInteger
import javax.crypto.SecretKeyFactory
import java.security.MessageDigest
import javax.xml.bind.DatatypeConverter._
object Crypto extends App {
val aesKey = "d2cb415e067c7b13".getBytes("UTF-8")
val id = "aabb-1234";
val b64Data = """zWdR9lWKE2k1t3louxSsoK3E/xFkOrfDgXpsgSAfiOgFkrLVhz5OBqkKRSRRyxhX"""
val encryptedData:Array[Byte] = parseBase64Binary(b64Data)
val md5 = MessageDigest.getInstance("MD5")
md5.update(id.getBytes("UTF-8"))
val ivStr = new BigInteger(1, md5.digest()).toString(16).substring(0, 16)
val iv = ivStr.getBytes("UTF-8")
val decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding")
decrypt.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(iv))
val data = decrypt.doFinal(encryptedData)
val decryptedData = new String(data, "UTF-8")
println(decryptedData)
}
@trautvetter
Copy link

This is great - thanks for sharing.

@jpereira
Copy link

hi man! Thanks for share!!

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