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)
}
}
用kotlin实现RSA签名和验签
最新推荐文章于 2024-07-18 18:50:15 发布