用Kotlin實現RSA加密使用公鑰做加密
import java.math.BigInteger
import java.security.KeyFactory
import java.security.PublicKey
import java.security.spec.RSAPublicKeySpec
import javax.crypto.Cipher
object RSAEncryptUtil {
private var n: BigInteger? = null
private var e: BigInteger? = null
private var result: String? = null
/**
* RSA加密
*
* @param password 內容
*/
fun RSAEncrypt(password: ByteArray): String? {
if (password.isEmpty()) {
return null
}
val keySpec = RSAPublicKeySpec(n, e)
val kf: KeyFactory = KeyFactory.getInstance("RSA")
val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
val keyPublic: PublicKey = kf.generatePublic(keySpec)
cipher.init(Cipher.ENCRYPT_MODE, keyPublic)
val encryptData: ByteArray = cipher.doFinal(password)
return encryptData.toHexString()
}
fun setPublic(keyModule: String?, keyExponent: String?) {
if (keyModule == null && keyExponent == null) {
n = null
e = null
result = null
return
}
n = BigInteger(keyModule, 16)
e = BigInteger(keyExponent, 16)
}
}
其中toHexString
為Kotlin的extension