kotlin之RSA加解密

import java.security.KeyPairGenerator
import java.security.PrivateKey
import java.security.PublicKey
import java.util.*
import javax.crypto.Cipher

class RSACrypt {

    val transformation = "RSA"
    var publicKey: PublicKey? = null
    var privateKey: PrivateKey? = null

    fun keyPairGenerator(){
        val generator = KeyPairGenerator.getInstance("RSA")
        val keyPair = generator.genKeyPair()

        publicKey = keyPair.public
        privateKey = keyPair.private

        if (publicKey != null && privateKey != null){
            println(Base64.getEncoder().encodeToString(publicKey?.encoded))
            println(Base64.getEncoder().encodeToString(privateKey?.encoded))
        }
    }

    //公钥加密(当然也可以私钥加密)
    fun encryptByPublicKey(input: String):String{
        //1 创建cipher对象
        val cipher = Cipher.getInstance(transformation)

        //2 初始化cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, publicKey)

        //3 加密或解密
        val encrypt = cipher.doFinal(input.toByteArray())

        return Base64.getEncoder().encodeToString(encrypt)
    }

    //私钥解密(当然也可以公钥加密)
    fun dencryptByPrivateKey(input: String):String{
        //1 创建cipher对象
        val cipher = Cipher.getInstance(transformation)

        //2 初始化cipher对象
        cipher.init(Cipher.DECRYPT_MODE, privateKey)

        //3 解密
        val encrypt = cipher.doFinal(Base64.getDecoder().decode(input))

        return String(encrypt)
    }

}
    fun rsa加解密(){
        val rsa = RSACrypt()
        rsa.keyPairGenerator()
        var result =  rsa.encryptByPublicKey("公钥加密私钥解密;私钥加密公钥解密")
        println(result)
        println(rsa.dencryptByPrivateKey(result))
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值