cryptotest.frink

Download or view cryptotest.frink in plain text format


// Sample encryption and decryption in Frink using Java's cryptographic
// libraries.

// You would probably be better to use the more rigorous practices from
// this posting:
//
// http://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption
//
// which are encoded in the cryptoAES256.frink sample program.

// Create a hard-coded secret key for demonstration purposes.
// This is, of course, not what you'll want to do in practice.
msg = newJavaArray["byte", 16]                   // 16 bytes Java array
msg = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]    // assign value for the msg

// Algorithms like HTTPS exchange the secret key by a process like
// Diffie-Hellman key exchange.  Programs like gpg use something like
// public-key RSA encryption to exchange encrypted secret keys, which are then
// used to initialize the AES encryption which is used to encrypt the body of
// the message.

// Hash the secret key.
// Msg is the secret key that will be used for encryption.  Read PKCS #5 for
// a better way to do this than just hashing a password:
// http://www.rsa.com/rsalabs/node.asp?id=2127
x = callJava["java.security.MessageDigest", "getInstance", "MD5"]
x.update[msg]                                 // perform hash operation
d = x.digest[]                                // get digest to array d [0..15]

// turn d to a secret key s for AES
s=newJava["javax.crypto.spec.SecretKeySpec",[d,"AES"]] 

// constructor for AES encryption
c=callJava["javax.crypto.Cipher","getInstance","AES" ]

// text to be encrypted
text = "Frink rocks (or whatever you want to encrypt). \u263a"

// Coerce the text to a raw Java string so we can call its getBytes method
// with the specified encoding.  This allows us to handle characters above
// ASCII 127.
plaintextBytes = newJava["java.lang.String", text].getBytes["UTF-8"]

c.init[c.ENCRYPT_MODE, s]                          // set encryption mode (1)
ciphertext = c.doFinal[plaintextBytes]  // Perform the actual encryption
                                        // Returns a Java array of bytes.

println["Encrypted text:"]
for i = ciphertext
   print[padLeft[base[i<0 ? i+256 : i, 16],2,"0"]] // Bytes in Java are signed
println[]
println[]

// Decrypt
c.init[c.DECRYPT_MODE, s]                // set decryption mode (2), same key
ptxt = c.doFinal[ciphertext]

println["Decrypted text:"]
// Create a Unicode string from the bytes and specified encoding.
// the toString call forces a conversion from the raw Java String object
// to a Frink type.
println[newJava["java.lang.String",[ptxt, "UTF-8"]].toString[]]


Download or view cryptotest.frink in plain text format


This is a program written in the programming language Frink.
For more information, view the Frink Documentation or see More Sample Frink Programs.

Alan Eliasen was born 19966 days, 21 hours, 36 minutes ago.