Skip to content

Instantly share code, notes, and snippets.

@fomkin
Last active April 26, 2020 12:52
Show Gist options
  • Save fomkin/46f0e4da591ba96f12ee9430244649c9 to your computer and use it in GitHub Desktop.
Save fomkin/46f0e4da591ba96f12ee9430244649c9 to your computer and use it in GitHub Desktop.
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.SecureRandom;
val message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris commodo tempus pharetra. Sed non fermentum est, id volutpat risus. Sed lobortis et est at faucibus. Sed id leo porttitor, mollis felis id, rutrum est.";
val messageBytes = message.getBytes
val random = new SecureRandom()
val keyBytes = new Array[Byte](16)
val iv1Bytes = new Array[Byte](16)
val iv2Bytes = new Array[Byte](16)
random.nextBytes(keyBytes)
random.nextBytes(iv1Bytes)
random.nextBytes(iv2Bytes)
val key = new SecretKeySpec(keyBytes, "AES")
val iv1 = new IvParameterSpec(iv1Bytes)
val iv2 = new IvParameterSpec(iv2Bytes)
val cipher1 = Cipher.getInstance("AES/CBC/PKCS5Padding") // same as AES/CBC/PKCS7Padding used in WebCrypto
cipher1.init(Cipher.ENCRYPT_MODE, key, iv1)
val ciphertext = cipher1.doFinal(messageBytes)
val cipher2 = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher2.init(Cipher.DECRYPT_MODE, key, iv2)
val decryptedMessageBytes = cipher2.doFinal(ciphertext)
val decryptedMessage = new String(decryptedMessageBytes)
println(message); // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris commodo tempus pharetra. Sed non fermentum est, id volutpat risus. Sed lobortis et est at faucibus. Sed id leo porttitor, mollis felis id, rutrum est.
println(decryptedMessage); // ��{(<}����W�s�xr sit amet, consectetur adipiscing elit. Mauris commodo tempus pharetra. Sed non fermentum est, id volutpat risus. Sed lobortis et est at faucibus. Sed id leo porttitor, mollis felis id, rutrum est.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment