簡體   English   中英

使用 RSA 加密/解密字符串 .NET

[英]Encrypt/Decrypt strings with RSA .NET

.NET 6個項目有以下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);
    }
}

提供了RSAParameters ,沒問題
當我傳遞字符串a對其進行加密時,出現以下異常

System.FormatException:輸入不是有效的 Base-64 字符串,因為它包含非 base-64 字符、兩個以上的填充字符或填充字符中的非法字符。

此異常是從Convert.FromBase64String方法引發的,我理解這一點。

我的問題實際上是:如何將字符串參數轉換為 RSA class 所需的 byte[]?

注意: Encoding.UTF8.GetBytes()不起作用,它會拋出另一個異常

這是我找到的解決方案,對我有用

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM