用kotlin实现RSA签名和验签

import org.junit.jupiter.api.Test
import sun.misc.BASE64Decoder
import sun.misc.BASE64Encoder
import java.security.KeyFactory
import java.security.PrivateKey
import java.security.PublicKey
import java.security.Signature
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
import java.util.*


class RsaSignature {

    val privateKeyString = """MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALmZidD+6ouXfWNP
yUyPqR2Bgg8+YUrx3XDCezORlizvL327Ih6FuCMLbxZ/xpING4v+jUQvnz1jK6fa
5juzlCwouwayPmbVXmb3jFNlAhjmojbdpC6H+aWt5frVO1fTAMyUH7OVOIIlZaYR
ha1BI4GO3g96V7PqhSipazfxZVO7AgMBAAECgYBD8S/hQSAtP6SYEWIYU9LNyVYK
LITDQa0VlSwyoY3/HwQcm7+OutbAhXQCIX5YgtHduq6OEnzRpRcbGGgF3ORVcm62
LWU6wJaSEvRfBTJMLkgRGjOucwY1EDylijIwcJVO61W+4HqUo42AhJgZ9DYiIczP
QKUJfjqzMZGH/IgYaQJBANv9LEp3PHDXGiX2wHqmCFmfd/oLKlGR9P72sa2z2a1j
LXw2RdoQwVNydyrsO6ZjcpvhldhtYtqqQHk5/NJFge8CQQDX+0GfIhFD5OgipQO9
tc0KwFEQTKkvJxQN9cldOhovwWqLTtngOyE/4K30lP+5Set1kFaIJH3df4eP/xra
Uab1AkEAw3YhglCLPV+B9jVWNCONy8PrIBoHkc5zto6OtF3WjT5PzcuTKPw2KeTM
iTC4l1BJJsO7Fj+q08rt2khxoIrttQJAZ35yl3qPo2URB2jjPgjb1AcL0S+q8nlb
VsUsVIv++FtKXq7OIHC1IhLbyJONZpBRT+h2To6N8ZGmuA2aJHtz8QJAHcRAqmjb
VbVbJGlILPo5b/f7gkYtMULyPKD8Ej1OzEtzYGBjei4AGEs68j2vp8sB3QZOK0OR
JsCEslwstSLLVw=="""

    val publicKeyString = """MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5mYnQ/uqLl31jT8lMj6kdgYIP
PmFK8d1wwnszkZYs7y99uyIehbgjC28Wf8aSDRuL/o1EL589Yyun2uY7s5QsKLsG
sj5m1V5m94xTZQIY5qI23aQuh/mlreX61TtX0wDMlB+zlTiCJWWmEYWtQSOBjt4P
elez6oUoqWs38WVTuwIDAQAB"""

    @Test
    fun testSign() {
        var privateSign = Signature.getInstance("SHA256withRSA")
        val privateKey = getPrivateKey(privateKeyString)

        val sign = privateSign.run {
            initSign(privateKey)
            update("test".toByteArray())
            sign()
        }

        var signBase64 = Base64.getEncoder().encodeToString(sign);
        println(signBase64)


        var publicSignature = Signature.getInstance("SHA256withRSA")
        val publicKey = getPublicKey(publicKeyString)
        val verifyOK = publicSignature.run {
            initVerify(publicKey)
            update("test".toByteArray())
            verify(sign)
        }

        println(verifyOK)
    }

    /**
     * 得到公钥
     * @param key 密钥字符串(经过base64编码)
     * @throws Exception
     */
    @Throws(Exception::class)
    fun getPublicKey(key: String?): PublicKey? {
        val keyBytes: ByteArray = BASE64Decoder().decodeBuffer(key)
        val keySpec = X509EncodedKeySpec(keyBytes)
        val keyFactory: KeyFactory = KeyFactory.getInstance("RSA")
        return keyFactory.generatePublic(keySpec)
    }

    /**
     * 得到私钥
     * @param key 密钥字符串(经过base64编码)
     * @throws Exception
     */
    @Throws(Exception::class)
    fun getPrivateKey(key: String?): PrivateKey? {
        val keyBytes: ByteArray = BASE64Decoder().decodeBuffer(key)
        val keySpec = PKCS8EncodedKeySpec(keyBytes)
        val keyFactory: KeyFactory = KeyFactory.getInstance("RSA")
        return keyFactory.generatePrivate(keySpec)
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值