本文介绍了加密/解密字符串Kotlin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Kotlin中创建了这两个扩展来对字符串进行加密/解密:

I've created this two extensions in Kotlin to Encrypt/Decrypt strings:

fun String.encrypt(seed : String): String {
    val keyGenerator = KeyGenerator.getInstance("AES")
    val secureRandom = SecureRandom.getInstance("SHA1PRNG")
    secureRandom.setSeed(seed.toByteArray())

    keyGenerator.init(128, secureRandom)
    val skey = keyGenerator.generateKey()
    val rawKey : ByteArray = skey.encoded

    val skeySpec = SecretKeySpec(rawKey, "AES")
    val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec)
    val byteArray = cipher.doFinal(this.toByteArray())

    return byteArray.toString()
}

fun String.decrypt(seed : String): String {
    val keyGenerator = KeyGenerator.getInstance("AES")
    val secureRandom = SecureRandom.getInstance("SHA1PRNG")
    secureRandom.setSeed(seed.toByteArray())

    keyGenerator.init(128, secureRandom)
    val skey = keyGenerator.generateKey()
    val rawKey : ByteArray = skey.encoded

    val skeySpec = SecretKeySpec(rawKey, "AES")
    val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
    cipher.init(Cipher.DECRYPT_MODE, skeySpec)
    val byteArray = cipher.doFinal(this.toByteArray())

    return byteArray.toString()
}

由于某种原因,我收到以下异常:

for some reason I'm getting the following exception:

javax.crypto.IllegalBlockSizeException: last block incomplete in decryption

我做错了什么?

推荐答案

要对密文进行编码,请使用64位或十六进制. Java API包含Base64类,因此最好使用该类.

To encode your ciphertext use base 64 or hexadecimals. The Java API contains a Base64 class, so you're probably best off using that.

byte[]#toString不会执行您期望的操作;它只是返回字节数组引用的表示形式,而不是字节数组的内容.

byte[]#toString doesn't do what you expect it to do; it simply returns a representation of the byte array reference, not the contents of the byte array.

除此之外:

  • 不要使用SecureRandom派生密钥,请尝试查找PBKDF2;
  • 明确使用操作模式,例如"AES/GCM/NoPadding";
  • 使用唯一的IV,如果决定使用CBC(通常不安全),则使用随机IV;
  • 在未为消息明确选择字符编码的情况下,请勿使用toByteArray.
  • don't use SecureRandom to derive a key, try and lookup PBKDF2;
  • explicitly use a mode of operation such as "AES/GCM/NoPadding";
  • use a unique IV, and a random IV if you decide to use CBC (usually insecure);
  • don't use toByteArray without explicitly selecting a character encoding for the message.

这篇关于加密/解密字符串Kotlin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 20:56