Skip to content

Instantly share code, notes, and snippets.

@hisui
Created September 8, 2016 01:33
Show Gist options
  • Save hisui/b67726e744e92f2cc254b98706743e5b to your computer and use it in GitHub Desktop.
Save hisui/b67726e744e92f2cc254b98706743e5b to your computer and use it in GitHub Desktop.
import java.nio.charset.StandardCharsets.UTF_8
import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
object EasyCrypto {
private[this] val IV = "prVznW_57".getBytes(UTF_8)
private[this] def convert(src: Array[Byte], key: String, iv: Array[Byte], mode: Int): Array[Byte] = {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(mode, new SecretKeySpec(sha256(key.getBytes(UTF_8), 16), "AES"), new IvParameterSpec(sha256(iv, 16)))
cipher.doFinal(src)
}
private[this] def sha256(src: Array[Byte], n: Int): Array[Byte] =
java.security.MessageDigest.getInstance("SHA-256").digest(src).slice(0, n)
def encrypt(src: Array[Byte], key: String, iv: Array[Byte] = IV): String =
new String(Base64.getUrlEncoder.encode(convert(src, key, iv, Cipher.ENCRYPT_MODE)), UTF_8)
def decrypt(src: String, key: String, iv: Array[Byte] = IV): Array[Byte] =
convert(Base64.getUrlDecoder.decode(src), key, iv, Cipher.DECRYPT_MODE)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment