简体   繁体   中英

how to hash the value using private key in .pem file in C#

i am beginner to the c#, i have got the code in java and want to convert in C#

  private static String signSHA256RSA(String input, String strPk) throws Exception {

        byte[] b1 = Base64.getDecoder().decode(strPk);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(b1);
        KeyFactory kf = KeyFactory.getInstance("RSA");

        Signature privateSignature = Signature.getInstance("SHA256withRSA");
        privateSignature.initSign(kf.generatePrivate(spec));
        privateSignature.update(input.getBytes(StandardCharsets.UTF_8));
        byte[] s = privateSignature.sign();
        return Base64.getEncoder().encodeToString(s);
    }


output should have hash value

If your input and strPk parameters are base64String, the converted code may look like this:

private static string signSHA256RSA(string input, string strPk)
{
    byte[] b1 = Convert.FromBase64String(strPk);
            
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(b1);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey PrivateKey = kf.generatePrivate(spec);

    Signature privateSignature = Signature.getInstance("SHA256withRSA");
    privateSignature.initSign(kf.generatePrivate(spec));
    privateSignature.update(Encoding.UTF8.GetBytes(input));
    byte[] s = privateSignature.sign();
    return Convert.ToBase64String(s);
}

You need to install the IKVM Nuget package in order to use some classes. Some conversions in C# are probably these, hope this can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM