1

I have a tool which creates a signature. I am looking for equivalent code in dot net core 2.1.

Java Code: sign(currentdate,'some text','SHA1WithRSA')

public String sign(String date, String subjectId, String algorithm){
    Signature rsa = Signature.getInstance(algorithm);
    rsa.initSign(this.getPrivate());
    rsa.update(subjectId.getBytes());
    rsa.update(date.getBytes());
    String signature = new String(Base64.getEncoder().encode(rsa.sign()));
    return signature;
}

public PrivateKey getPrivate() {
    String privateKeyPEM = "<This is the private key string";

    byte[] encoded = Base64.getDecoder().decode(privateKeyPEM);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(encoded);
    return kf.generatePrivate(spec);
}

Suggest a way to generate dot net core 2.1 equivalent code for the above with or without 3rd party tool.

1
  • 1
    What did you try so far? Commented May 10, 2021 at 5:53

1 Answer 1

1

This is work for me using Portable.BouncyCastle library.

 private string GetSign(string data)
        {
            using (var rsa = new RSACryptoServiceProvider())
            {
                var privateKey = new StringBuilder();
                privateKey.AppendLine("-----BEGIN RSA PRIVATE KEY-----");
                privateKey.AppendLine("private key as string");
                privateKey.AppendLine("-----END RSA PRIVATE KEY-----");

                var pem = new PemReader(new StringReader(privateKey.ToString()));
                var keyPair = (AsymmetricCipherKeyPair)pem.ReadObject();
                var privateKeyParameters = (RsaPrivateCrtKeyParameters)keyPair.Private;
                var rsaParameters = DotNetUtilities.ToRSAParameters(privateKeyParameters);

                rsa.ImportParameters(rsaParameters);
                var sign = rsa.SignData(Encoding.UTF8.GetBytes(data), new HashAlgorithmName("SHA1") /*pass your algorithm*/,
                    RSASignaturePadding.Pkcs1);

                return Convert.ToBase64String(sign);
            }
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.