简体   繁体   中英

Encrypt/Decrypt strings with RSA .NET

.NET 6 project has the following class

using System.Security.Cryptography;

internal sealed class EncryptionService
{
    private readonly RSAParameters _rsaParameters;

    public EncryptionService(RSAParameters rsaParameters)
    {
        _rsaParameters = rsaParameters;
    }

    public string Decrypt(string encryptedText)
    {
        using RSA rsa = RSA.Create(_rsaParameters);

        byte[] plainTextBytes = Convert.FromBase64String(encryptedText);

        byte[] decryptedTextBytes = rsa.Decrypt(plainTextBytes, RSAEncryptionPadding.OaepSHA256);

        return Convert.ToBase64String(decryptedTextBytes);
    }

    public string Encrypt(string plainText)
    {
        using RSA rsa = RSA.Create(_rsaParameters);

        byte[] plainTextBytes = Convert.FromBase64String(plainText);

        byte[] encryptedTextBytes = rsa.Encrypt(plainTextBytes, RSAEncryptionPadding.OaepSHA256);

        return Convert.ToBase64String(encryptedTextBytes);
    }
}

The RSAParameters is provided and no problem with that
when I pass string a to encrypt it, I get the following exception

System.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

This exception is raised from Convert.FromBase64String method and I understand that.

My Question actually is: how I can convert the string parameter to the byte[] that is needed by the RSA class?

NOTE: Encoding.UTF8.GetBytes() does not work, it throws another exception

Here is the solution I reached and that worked for me

using System.Security.Cryptography;
using System.Text;

internal sealed class RSAEncryptionService
{
    private readonly RSAParameters _rsaParameters;

    public RSAEncryptionService(RSAParameters rsaParameters)
    {
        _rsaParameters = rsaParameters;
    }

    public string Encrypt(string plainText)
    {
        using RSA rsa = RSA.Create(_rsaParameters);

        byte[] plainTextBytes = Encoding.Unicode.GetBytes(plainText);

        byte[] encryptedTextBytes = rsa.Encrypt(plainTextBytes, RSAEncryptionPadding.OaepSHA256);

        return Convert.ToBase64String(encryptedTextBytes);
    }

    public string Decrypt(string encryptedText)
    {
        using RSA rsa = RSA.Create(_rsaParameters);

        byte[] plainTextBytes = Convert.FromBase64String(encryptedText);

        byte[] decryptedTextBytes = rsa.Decrypt(plainTextBytes, RSAEncryptionPadding.OaepSHA256);

        return Encoding.Unicode.GetString(decryptedTextBytes);
    }
}

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