Skip to content

Instantly share code, notes, and snippets.

@alexandru
Last active August 23, 2022 13:18
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save alexandru/ac1c01168710786b54b0 to your computer and use it in GitHub Desktop.
Save alexandru/ac1c01168710786b54b0 to your computer and use it in GitHub Desktop.
import java.security.MessageDigest
import java.util
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import org.apache.commons.codec.binary.Base64
/**
* Sample:
* {{{
* scala> val key = "My very own, very private key here!"
*
* scala> Encryption.encrypt(key, "pula, pizda, coaiele!")
* res0: String = 9R2vVgkqEioSHyhvx5P05wpTiyha1MCI97gcq52GCn4=
*
* scala> Encryption.decrypt(key", res0)
* res1: String = pula, pizda, coaiele!
* }}}
*/
object Encryption {
def encrypt(key: String, value: String): String = {
val cipher: Cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, keyToSpec(key))
Base64.encodeBase64String(cipher.doFinal(value.getBytes("UTF-8")))
}
def decrypt(key: String, encryptedValue: String): String = {
val cipher: Cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING")
cipher.init(Cipher.DECRYPT_MODE, keyToSpec(key))
new String(cipher.doFinal(Base64.decodeBase64(encryptedValue)))
}
def keyToSpec(key: String): SecretKeySpec = {
var keyBytes: Array[Byte] = (SALT + key).getBytes("UTF-8")
val sha: MessageDigest = MessageDigest.getInstance("SHA-1")
keyBytes = sha.digest(keyBytes)
keyBytes = util.Arrays.copyOf(keyBytes, 16)
new SecretKeySpec(keyBytes, "AES")
}
private val SALT: String =
"jMhKlOuJnM34G6NHkqo9V010GhLAqOpF0BePojHgh1HgNg8^72k"
}
@fulopm
Copy link

fulopm commented Nov 13, 2016

You are using a constant salt and SHA-1, which are not too great!

@doruchiulan
Copy link

au inceput razboaiele

@rajesh-jayagopi
Copy link

That's not a matter, you could change to other algorithms, such as MD5, SHA-2, etc.

@LtHummus
Copy link

In addition to the issues that fulopm pointed out, this code also encrypts using ECB mode, which is insecure.

@guizmaii
Copy link

Hi everyone,

I tried to create an updated version which follows your remarks and the best practices. I'd love to have your feedback on it too.

Here's the code: https://gist.github.com/guizmaii/6b5d3666081960639c3df0a24e17e2fd

@alexandru
Copy link
Author

@guizmaii gists are not meant for libraries man 😛 otherwise looking good.

@truongkendy
Copy link

truongkendy commented Oct 26, 2020

Do you have the implementation in python?

@nickfun
Copy link

nickfun commented Aug 2, 2021

@alexandru is there a license you release this under?

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