MeTitus
MeTitus

Reputation: 3428

Sign document using RSA

I haven't done anything similar before and after reading about this I'm still not sure on how to progress.

I have a RSA private key which is protected using a password, stored as text in the local database, and this is my fist problem, how to get the orginal RSA private key.

The second part, relates to signing a document. Basically I have the following method signature which I have to implement:

string GenerateDocumentSignature(string privateKey, string password, string documentId)

So within this methods I will have to reverse the private key and thena apply a RSA encryption.

Can you guys shed some light on how to archive this? Thanks

Upvotes: 0

Views: 222

Answers (1)

MeTitus
MeTitus

Reputation: 3428

I was able to get it working using BouncyCastle:

public class SignDocsProvider : ISignDocsProvider
{
    public string GenerateSignature(string privateKey, string password, string documentId)
    {
        var keyPair = ReadPrivateKey(privateKey, password);
        var sha1Digest = new Sha1Digest();
        var rsaDigestSigner = new RsaDigestSigner(sha1Digest);

        rsaDigestSigner.Init(true, keyPair);

        var documentIdToSign = Encoding.ASCII.GetBytes(documentId);

        rsaDigestSigner.BlockUpdate(documentIdToSign, 0, documentIdToSign.Length);

        return Convert.ToBase64String(rsaDigestSigner.GenerateSignature());
    }

    private static AsymmetricKeyParameter ReadPrivateKey(string privateKey, string password)
    {
        AsymmetricCipherKeyPair keyPair;

        using (var reader = new StringReader(privateKey))
            keyPair = (AsymmetricCipherKeyPair)new PemReader(reader, new PasswordFinder(password)).ReadObject();

        return keyPair.Private;
    }
}

internal class PasswordFinder : IPasswordFinder
{
    private readonly string _password;


    public PasswordFinder(string password)
    {
        _password = password;
    }


    public char[] GetPassword()
    {
        return _password.ToCharArray();
    }
}

Upvotes: 1

Related Questions