【发布时间】:2021-06-03 23:42:31
【问题描述】:
我有一个用 Koltin 编写的包,我想用 Dart 重写它。我一直在尝试使用encrypt 和pointycastle。但是我遇到了问题
我将如何在 Dart 中编写这个实现。
我已经开始尝试对公钥进行编码
var modulusBytes = base64.decode(publicKey!);
import android.util.Base64
import java.security.KeyFactory
import java.security.NoSuchAlgorithmException
import java.security.PublicKey
import java.security.spec.InvalidKeySpecException
import java.security.spec.X509EncodedKeySpec
import javax.crypto.Cipher
object Crypto {
private const val PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADfafwfegRHqfkBiKGn/rrgrgrgrrgg" +
"2wkeSokw2OJrCI+d6YGJPrHHx+nmb/Qn885/R01Gw6d7M824qofmCvkCAwEAAQ=="
private const val ALGORITHM = "RSA"
private const val CIPHER = "RSA/ECB/PKCS1Padding"
private fun encrypt(text: String, key: PublicKey): ByteArray? {
var cipherText: ByteArray? = null
try {
// get an RSA cipher object
val cipher = Cipher.getInstance(CIPHER)
//init cipher and encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, key)
cipherText = cipher.doFinal(text.toByteArray())
} catch (e: Exception) {
e.printStackTrace()
}
return cipherText
}
如何在 Dart 中使用字节数组?
我也有这个作为尝试在 Koltin 中加密数据的一部分。
@Throws(SecurityException::class)
fun encrypt(text: String): String {
return String(Base64.encode(encrypt(text, getPublicKeyFromString(PUBLIC_KEY)), Base64.NO_WRAP))
}
@Throws(SecurityException::class)
private fun getPublicKeyFromString(pubKey: String): PublicKey {
val key: PublicKey
try {
//init keyFactory
val kf = KeyFactory.getInstance(ALGORITHM)
//decode the key into a byte array
val keyBytes = Base64.decode(pubKey, Base64.NO_WRAP)
//create spec
val spec = X509EncodedKeySpec(keyBytes)
//generate public key
key = kf.generatePublic(spec)
} catch (e: InvalidKeySpecException) {
throw SecurityException("Invalid public key: " + e.message)
} catch (e: NoSuchAlgorithmException) {
throw SecurityException("Invalid public key: " + e.message)
}
return key
}
}
【问题讨论】:
-
你看过pub.dev/packages/rsa_encrypt吗?最近好像更新了。
-
@RandalSchwartz 我已经检查过了。我在使用它时遇到了麻烦,因为它没有给我想要的东西。如果您可以使用它将我的实现从 Kotlin 重写为 Dart。我会更好理解的!
标签: android flutter kotlin dart encryption