Kotlin实现SHA-256哈希和RSA签名

07-19 1956阅读

1. 对一段原始字符串,实现SHA 哈希签名,即hashMessage;

Kotlin实现SHA-256哈希和RSA签名
(图片来源网络,侵删)

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)

}

VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]