Last active
October 2, 2020 04:01
-
-
Save satorg/008e97daa9dcba4d700426be040b7a80 to your computer and use it in GitHub Desktop.
Simple message encryption/decryption with AES
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
iv
must be recreated for each message with the samekey