Android加密算法之RSA(一)

Kornan
2020-09-15 / 0 评论 / 363 阅读 / 正在检测是否收录...
RSA公钥加密私钥解密
object RSACrypt {

    private const val transformation = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"

    /**
     * 公钥加密
     * @param input 原文
     * @param publicKey 公钥
     */
    fun encryptByPublicKey(input: ByteArray, publicKey: PublicKey): String {
        val cipher = Cipher.getInstance(transformation)//创建cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, publicKey)//初始化cipher对象
        val encrypt = cipher.doFinal(input) //加密或解密
        return Base64.encodeToString(encrypt, Base64.NO_WRAP)
    }

    /**
     * 私钥解密
     * @param input 密文
     * @param privateKey 私钥
     */
    fun decryptByPrivateKey(input: ByteArray, privateKey: PrivateKey): String {
        val cipher = Cipher.getInstance(transformation) //创建cipher对象
        cipher.init(Cipher.DECRYPT_MODE, privateKey)//初始化cipher对象
        val encrypt = cipher.doFinal(input)//加密或解密
        return String(encrypt)
    }
    //生成RSAKey
    fun generateRSAKeyPair(keyLength: Int): KeyPair? {
        return try {
            val kpg = KeyPairGenerator.getInstance("RSA")
            kpg.initialize(keyLength)
            kpg.genKeyPair()
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
            null
        }
    }
}
调用方法
var keyPair = RSACrypt.generateRSAKeyPair(2048)
        keyPair?.let {
            val input = "123木头人"
            val encryptPublicKey = RSACrypt.encryptByPublicKey(input.encodeToByteArray(), it.public)
            val decryptPrivateKey = RSACrypt.decryptByPrivateKey(Base64.decode(encryptPublicKey, Base64.NO_WRAP), it.private)
            Log.w("rsa", "公钥加密 $encryptPublicKey")
            Log.w("rsa", "私钥解密 $decryptPrivateKey")
        }
注意加密时如果内容过长会报:
Caused by: javax.crypto.IllegalBlockSizeException: input must be under 256 bytes
0

评论 (0)

取消