如何获得相同的加密文本

时间:2019-04-11 15:47:44

标签: android kotlin secure-random

我有以下代码,它可以正常工作而不会出现问题,但我想获得相同的加密文本。我认为解决方案不使用SecureRandom,因为问题在于我尝试在与第一次加密不同的时刻解密数据

我正在使用以下内容:

  • Android Studio
  • 科特林
  • Java版本1.8
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))
    }
}

0 个答案:

没有答案