我有以下代码,它可以正常工作而不会出现问题,但我想获得相同的加密文本。我认为解决方案不使用SecureRandom
,因为问题在于我尝试在与第一次加密不同的时刻解密数据
我正在使用以下内容:
package com.xxxx
import android.util.Base64
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
class EncryptDecrypt {
var decrypted = ""
var encrypted = ""
fun main(textToWork: String, flag: Boolean) {
val password = "**hola1234como**"
val r = SecureRandom()
r.setSeed(r.generateSeed(16))
val byteIV = ByteArray(16)
r.nextBytes(byteIV)
val encryptText = if(flag) encrypt(textToWork, password, byteIV) else textToWork
val bytes = Base64.decode(encryptText, Base64.DEFAULT)
encrypted = encrypt(textToWork, password, byteIV)
decrypted = decrypt(bytes, password, byteIV)
}
private fun encrypt(plainText: String, password: String, byteIV: ByteArray): String {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
val key = SecretKeySpec(password.toByteArray(charset("UTF-8")), "AES")
cipher.init(Cipher.ENCRYPT_MODE, key, IvParameterSpec(byteIV))
val bytes = cipher.doFinal(plainText.toByteArray(charset("UTF-8")))
return Base64.encodeToString(bytes, Base64.DEFAULT)
}
private fun decrypt(bytes: ByteArray, password: String, byteIV: ByteArray): String {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
val key = SecretKeySpec(password.toByteArray(charset("UTF-8")), "AES")
cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(byteIV))
return String(cipher.doFinal(bytes))
}
}