Kotlin实现SHA-256哈希和RSA签名
1. 对一段原始字符串,实现SHA 哈希签名,即hashMessage;
2. 用私钥key 对SHA后的字符串信息签名,即signatureMessage;
3. 用公钥key验证私钥签名的信息(私钥签名的原始字符串是SHA-256哈希的字符串,即hashMessage)是否正确;
import java.security.MessageDigest
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 org.bouncycastle.util.encoders.Hex
// 对原始字符串传SHA-256哈希
fun sha256(input: String): String {
val bytes = input.toByteArray()
val md = MessageDigest.getInstance("SHA-256")
val digest = md.digest(bytes)
return Hex.toHexString(digest)
}
// 加载私钥信息
fun loadPrivateKey(privateKeyPEM: String): PrivateKey {
val privateKeyPEMStripped = privateKeyPEM
.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replace("\n", "")
val encoded = Hex.decode(privateKeyPEMStripped)
val keySpec = PKCS8EncodedKeySpec(encoded)
val keyFactory = KeyFactory.getInstance("RSA")
return keyFactory.generatePrivate(keySpec)
}
// 加载公钥信息
fun loadPublicKey(publicKeyPEM: String): PublicKey {
val publicKeyPEMStripped = publicKeyPEM
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replace("\n", "")
val encoded = Hex.decode(publicKeyPEMStripped)
val keySpec = X509EncodedKeySpec(encoded)
val keyFactory = KeyFactory.getInstance("RSA")
return keyFactory.generatePublic(keySpec)
}
// 使用私钥key 对SHA-256哈希后的字符串签名
fun signMessage(message: String, privateKey: PrivateKey): String {
val signature = Signature.getInstance("SHA256withRSA")
signature.initSign(privateKey)
signature.update(message.toByteArray())
val signedBytes = signature.sign()
return Hex.toHexString(signedBytes)
}
//使用公钥钥key 对私钥签名的SHA-256哈希的字符串 验证:message 是对原始字符串 SHA-256哈希后的字符串; signedMessage 是私钥签名后的字符串;publicKey - 公钥key
fun verifySignature(message: String, signedMessage: String, publicKey: PublicKey): Boolean {
val signature = Signature.getInstance("SHA256withRSA")
signature.initVerify(publicKey)
signature.update(message.toByteArray())
val signedBytes = Hex.decode(signedMessage)
return signature.verify(signedBytes)
}
//示例如下
fun main() {
val message = "Test"
val privateKeyPEM = ""
val publicKeyPEM = ""
val hashMsg = sha256(message)
// 加载私钥和公钥
val privateKey = loadPrivateKey(privateKeyPEM)
val publicKey = loadPublicKey(publicKeyPEM)
// 使用私钥签名
val signatureMessage = signMessage(hashMsg, privateKey)
// 使用公钥验证签名信息
val isVerified = verifySignature(hashMsg, signatureMessage, publicKey)
}
原文地址:https://blog.csdn.net/qq_27247815/article/details/140530036
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!