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)) }