/Rfc2898Crypto.scala Secret
Last active
March 19, 2021 09:04
Crypto Encryption Decryption
This file contains hidden or 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
// pasted it to ammonite | |
interp.load.ivy("commons-codec" % "commons-codec" % "1.10") // to use Base64 | |
import org.apache.commons.codec.binary._ | |
import java.nio.charset.StandardCharsets | |
import javax.crypto._ | |
import javax.crypto.spec._ | |
object Rfc2898Crypto { | |
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1") | |
val bookingIdKey = "agoda2009!@".toCharArray | |
val salt = "As@3sd#2342Tscs%^$#@!frs".getBytes("UTF-8") | |
val pbeKeySpec = new javax.crypto.spec.PBEKeySpec(bookingIdKey, salt, 1000, 384) | |
val secretKey = factory.generateSecret(pbeKeySpec) | |
val key = new Array[Byte](32) | |
val iv = new Array[Byte](16) | |
System.arraycopy(secretKey.getEncoded, 0, key, 0, 32) | |
System.arraycopy(secretKey.getEncoded, 32, iv, 0, 16) | |
val secret = new SecretKeySpec(key, "AES") | |
val ivSpec = new IvParameterSpec(iv) | |
def encrypt(plainText: String) = { | |
try { | |
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") | |
cipher.init(Cipher.ENCRYPT_MODE, secret, ivSpec) | |
val result = cipher.doFinal(plainText.getBytes("UTF-8")) | |
Some(Base64.encodeBase64String(result)) | |
} catch { | |
case e: Exception => { | |
println(s"Failed to encrypt $plainText : ${e.getMessage}") | |
None | |
} | |
} | |
} | |
def decrypt(encoded: String) = { | |
try { | |
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") | |
cipher.init(Cipher.DECRYPT_MODE, secret, ivSpec) | |
val result = cipher.doFinal(Base64.decodeBase64(encoded)) | |
new String(result, StandardCharsets.UTF_8) | |
} catch { | |
case e: Exception => { | |
println(s"Failed to decrypt $encoded : ${e.getMessage}") | |
None | |
} | |
} | |
} | |
} | |
defined object Rfc2898Crypto | |
@ val id = "552097757" | |
id: String = "552097757" | |
@ Rfc2898Crypto.decrypt(Rfc2898Crypto.encrypt(id).get) == id | |
res7: Boolean = true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment