2014-09-23 32 views
1

我試圖創建一個X509Certificate2對象與一個公共的rsa密鑰加密在Unity與c#。我收到以下例外情況:ArgumentOutOfRangeException當調用X509Certificate2

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

爲了記錄在案:data.Length是784個

任何想法?

+2

爲什麼你認爲你的數據代表一個X509證書? – 2014-09-23 11:19:45

+0

我生成並編碼了java中的密鑰。它不適用於「----- BEGIN PUBLIC KEY -----」和「----- END PUBLIC KEY -----」 – cbacon 2014-09-23 11:54:09

+1

這是因爲它不是X509證書。 – 2014-09-23 21:31:59

回答

0

感謝您的幫助。證書是defenely不是一個關鍵,所以我終於設法得到一個工作函數來加密與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; 
}