Skip to content

Instantly share code, notes, and snippets.

@satorg
Last active October 2, 2020 04:01
Show Gist options
  • Save satorg/008e97daa9dcba4d700426be040b7a80 to your computer and use it in GitHub Desktop.
Save satorg/008e97daa9dcba4d700426be040b7a80 to your computer and use it in GitHub Desktop.
Simple message encryption/decryption with AES
val iv = new IvParameterSpec(Base64.getDecoder.decode("V4kfws5dKNgK0ORjb8jCtQ=="))
def mkKeySpec(key: String, load: Int) = {
val digest = MessageDigest.getInstance("SHA-256")
var bytes = key.getBytes(UTF_8)
for (_ <- 0 until load) {
bytes = digest.digest(bytes)
}
new SecretKeySpec(bytes, "AES")
}
def encrypt(msg: String, key: String, load: Int): String = {
val cipher = Cipher.getInstance("AES/CTR/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, mkKeySpec(key, load), iv)
val msgBytes = msg.getBytes(UTF_8)
val encBytes = cipher.doFinal(msgBytes)
Base64.getEncoder.encodeToString(encBytes)
}
def decrypt(msg: String, key: String, load: Int): String = {
val cipher = Cipher.getInstance("AES/CTR/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, mkKeySpec(key, load), iv)
val msgBytes = Base64.getDecoder.decode(msg)
val decBytes = cipher.doFinal(msgBytes)
new String(decBytes, UTF_8)
}
@satorg
Copy link
Author

satorg commented Sep 20, 2020

iv must be recreated for each message with the same key

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