调用X509Certificate2时出现ArgumentOutOfRangeException

本文关键字:ArgumentOutOfRangeException X509Certificate2 调用 | 更新日期: 2023-09-27 18:23:59

我尝试使用公共rsa密钥创建一个X509Certificate2对象,以便在Unity中使用c#进行加密。我得到以下异常:

> ArgumentOutOfRangeException: Cannot be negative. 
> Parameter name: length 
> System.String.Substring (Int32 startIndex, Int32 length) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/String.cs:348)
> Mono.Security.X509.X509Certificate.PEM (System.String type, System.Byte[] data) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/Mono.Security.X509/X509Certificate.cs:601)

static loadKey() {
    //get rsa public key
    byte[] data = GetBytes("MIIBIjANBgkqhk......EuH+zIXFzvirHQ2AxE/5wIDAQAB");
    Debug.Log(data.Length);
    X509Certificate2 x509certificate = new X509Certificate2(data);
    //[...]
}

这是GetBytes函数

static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

记录:数据。长度为784

有什么想法吗?

调用X509Certificate2时出现ArgumentOutOfRangeException

感谢您的帮助。证书不是密钥,所以我终于找到了一个工作函数,用bouncycastle加密字符串:

static string Encrypt2(string publicKeyFileName, string inputMessage)
{  
    try
    {
        // Converting the string message to byte array
        System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
        byte[] inputBytes = enc.GetBytes(inputMessage);
        AsymmetricKeyParameter publicKey = ReadAsymmetricKeyParameter(publicKeyFileName);
        // Creating the RSA algorithm object
        IAsymmetricBlockCipher cipher =  new Pkcs1Encoding(new RsaEngine());
        // Initializing the RSA object for Encryption with RSA public key. Remember, for encryption, public key is needed
        cipher.Init(true, publicKey);
        //Encrypting the input bytes
        byte[] cipheredBytes = cipher.ProcessBlock(inputBytes, 0, inputBytes.Length);
        return Convert.ToBase64String(cipheredBytes);
    }
    catch (Exception ex)
    {
        // Any errors? Show them
        Debug.Log("Exception encrypting file! More info:");
        Debug.Log(ex.Message);
    }
    return "";
}

public static AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename)
{
    var fileStream = System.IO.File.OpenText(pemFilename);
    var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(fileStream);
    var KeyParameter = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)pemReader.ReadObject();
    return KeyParameter;
}
相关文章:
  • 没有找到相关文章