Last active
August 23, 2022 13:18
-
-
Save alexandru/ac1c01168710786b54b0 to your computer and use it in GitHub Desktop.
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
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" | |
} |
au inceput razboaiele
That's not a matter, you could change to other algorithms, such as MD5, SHA-2, etc.
In addition to the issues that fulopm pointed out, this code also encrypts using ECB mode, which is insecure.
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
@guizmaii gists are not meant for libraries man 😛 otherwise looking good.
Do you have the implementation in python?
@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
You are using a constant salt and SHA-1, which are not too great!