Skip to content

Commit

Permalink
Crop private key to 16 bytes in V0 encryption-decryption
Browse files Browse the repository at this point in the history
  • Loading branch information
migesok committed Apr 2, 2020
1 parent 8e768f6 commit accbbee
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 17 deletions.
14 changes: 2 additions & 12 deletions src/main/scala/com/evolutiongaming/crypto/Crypto.scala
Expand Up @@ -15,14 +15,6 @@ import org.apache.commons.codec.digest.DigestUtils
* Based on https://github.com/playframework/playframework/blob/master/framework/src/play/src/main/scala/play/api/libs/Crypto.scala
*/
object Crypto {
// max allowed length in bytes
// For AES we hardcode key length to 128bit minimum to not depend on environment security policy settings:
// it may vary between 128 and 256 bits which can yield different encryption keys if we don't
val AesKeyBytesMaxSize: Int = 16

class AesKeyTooLong extends Exception(
s"AES key should have size no more than $AesKeyBytesMaxSize bytes"
)
class DecryptAuthException(cause: Throwable) extends Exception(
"Decrypted value is not the original one, most likely wrong private key used for decryption",
cause,
Expand Down Expand Up @@ -88,13 +80,11 @@ object Crypto {
private object AES_V0 {
private val CipherAlgorithm = "AES"
private val CipherTransformation = "AES"
private val KeySizeBytes: Int = 16 //128 bit

def decrypt(value: String, privateKey: String): String = {
val privateKeyBytes = privateKey.getBytes(UTF_8)
if (privateKeyBytes.length > AesKeyBytesMaxSize) {
throw new AesKeyTooLong
}
val effectiveSecretKey = privateKeyBytes.take(AesKeyBytesMaxSize)
val effectiveSecretKey = privateKeyBytes.take(KeySizeBytes)
val skeySpec = new SecretKeySpec(effectiveSecretKey, CipherAlgorithm)
val cipher = Cipher.getInstance(CipherTransformation)
cipher.init(Cipher.DECRYPT_MODE, skeySpec)
Expand Down
Expand Up @@ -12,7 +12,7 @@ object DecryptConfig {
config.getBoolean(EncryptedPasswordsPath)
) {
val secret = config getString AppSecretPath
Crypto.decryptAES(password, secret.substring(0, 16))
Crypto.decryptAES(password, secret)
} else {
password
}
Expand Down
8 changes: 5 additions & 3 deletions src/test/scala/com/evolutiongaming/crypto/CryptoSpec.scala
Expand Up @@ -69,9 +69,11 @@ class CryptoSpec extends AnyFlatSpec with Matchers {
}

it should "not decrypt with key bigger than 16 bytes" in {
assertThrows[Crypto.AesKeyTooLong](
Crypto.decryptAES("3d458dc2fe2cd11b9e42b2fee8b51f33", "1234567890123456now_it_became_too_long")
)
val key = "1234567890123456" + "now_it_became_too_long"
val original = "secretvalue"

val encrypted = "3d458dc2fe2cd11b9e42b2fee8b51f33"
Crypto.decryptAES(encrypted, key) shouldEqual original
}

it should "decrypt with key up to 16 bytes (v1)" in {
Expand Down
2 changes: 1 addition & 1 deletion version.sbt
@@ -1 +1 @@
version in ThisBuild := "2.0.1-SNAPSHOT"
version in ThisBuild := "3.0.0-SNAPSHOT"

0 comments on commit accbbee

Please sign in to comment.