c#中使用openssl
近期使用加密狗對軟件進行加密,但是軟件用的c#,這就比較坑了,因為c#自帶的System.Security.Cryptography只支持c#格式的公鑰加密私鑰解密,而現在需要私鑰加密公鑰解密。于是網上進行資料查找,一堆資料說的都是使用BouncyCastle,但是。。。。。。沒有使用不同格式的密文啊喂,你們有考慮過c#的孤獨嗎?
經過對結構體的分析,發現還是有些共通的地方,比如要有Modulus和Exponent,當然是對公鑰來說,然后各種調用,生成公鑰,一波操作猛如虎,回頭一看二百五啊。。。。。。沒人跟我說密文格式的不同啊喂。又是一頓搜索,知道了c#的rsa密文是xml格式的,不是簡單的base64的,需要轉換,咋辦?我想了個辦法,先用c#自帶的加解密生成一個公私鑰對,然后就知道格式了啊對不對,按照這個格式,我將openssl里的公鑰拼湊進去,得到一個xml格式的公鑰,再通過c#自帶的解xml公鑰,得到rsa信息,再生成base64格式的公鑰串,啊哈,竟然成功了,神奇不?
xml公鑰格式大概是這樣的:
string strPubKey = "<RSAKeyValue><Modulus>" + str64Modulus + "</Modulus><Exponent>" + str64Exponent + "</Exponent></RSAKeyValue>";
轉換xml格式公鑰:
public static string FromXmlPublicKey(string xmlPublicKey)
? ? ? ? {
? ? ? ? ? ? string result = string.Empty;
? ? ? ? ? ? using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
? ? ? ? ? ? {
? ? ? ? ? ? ? ? rsa.FromXmlString(xmlPublicKey);
? ? ? ? ? ? ? ? RSAParameters p = rsa.ExportParameters(false);
? ? ? ? ? ? ? ? RsaKeyParameters keyParams = new RsaKeyParameters(
? ? ? ? ? ? ? ? ? ? false, new BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent));
? ? ? ? ? ? ? ? SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyParams);
? ? ? ? ? ? ? ? result = Convert.ToBase64String(publicKeyInfo.ToAsn1Object().GetEncoded());
? ? ? ? ? ? }
? ? ? ? ? ? return result;
? ? ? ? }
用公鑰解密:
public static string DecryptPublicKey(string publicKey, string data)
? ? ? ? {
? ? ? ? ? ? RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
? ? ? ? ? ? byte[] cipherbytes = Convert.FromBase64String(data);
? ? ? ? ? ? RsaEngine rsa = new RsaEngine();
? ? ? ? ? ? rsa.Init(false, publicKeyParam);
? ? ? ? ? ? cipherbytes = rsa.ProcessBlock(cipherbytes, 0, cipherbytes.Length);
? ? ? ? ? ? return Convert.ToBase64String(cipherbytes, 0, cipherbytes.Length);
? ? ? ? }
以上,問題解決,如果大家有更好的辦法,希望留言,沒有人寫相關的東西,所以我粗略的寫了點,不對的請指出,謝謝!
總結
以上是生活随笔為你收集整理的c#中使用openssl的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle13001,安装oracle
- 下一篇: c#调用c++的dll接口