最近做項目接觸了一些關於用CA證書加密解密的知識,現在分享一下,加密主要分為對稱加密和非對稱加密以及單項加密這三種,CA是一個權威的第三方認證機構,CA加密有公鑰和私鑰之分。
以下是C#讀取證書文件進行加密解密的Code,供各位參考
CA 加密:
public static string CAEncryption(string xml) { X509Certificate2 pubcrt =new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + BaseConfig.CaPubkey); return Core.CaUtilHelper.Encrypt(xml, pubcrt); } public static String Encrypt(String plaintext, X509Certificate2 pubcrt) { X509Certificate2 _X509Certificate2 = pubcrt; using (RSACryptoServiceProvider RSACryptography = _X509Certificate2.PublicKey.Key as RSACryptoServiceProvider) { Byte[] PlaintextData = Encoding.UTF8.GetBytes(plaintext); int MaxBlockSize = RSACryptography.KeySize / 8 - 11; //加密塊最大長度限制 if (PlaintextData.Length <= MaxBlockSize) return Convert.ToBase64String(RSACryptography.Encrypt(PlaintextData, false)); using (MemoryStream PlaiStream = new MemoryStream(PlaintextData)) using (MemoryStream CrypStream = new MemoryStream()) { Byte[] Buffer = new Byte[MaxBlockSize]; int BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize); while (BlockSize > 0) { Byte[] ToEncrypt = new Byte[BlockSize]; Array.Copy(Buffer, 0, ToEncrypt, 0, BlockSize); Byte[] Cryptograph = RSACryptography.Encrypt(ToEncrypt, false); CrypStream.Write(Cryptograph, 0, Cryptograph.Length); BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize); } return Convert.ToBase64String(CrypStream.ToArray(), Base64FormattingOptions.None); } } }
CA 解密:
public static string CADecrypt(string content) { X509Certificate2 prvcrt = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + BaseConfig.CaPrvkey,BaseConfig.CaPwd, X509KeyStorageFlags.Exportable); return Core.CaUtilHelper.Decrypt(content, prvcrt); } public static String Decrypt(String ciphertext, X509Certificate2 prvpfx) { X509Certificate2 _X509Certificate2 = prvpfx; using (RSACryptoServiceProvider RSACryptography = _X509Certificate2.PrivateKey as RSACryptoServiceProvider) { Byte[] CiphertextData = Convert.FromBase64String(ciphertext); int MaxBlockSize = RSACryptography.KeySize / 8; //解密塊最大長度限制 if (CiphertextData.Length <= MaxBlockSize) return Encoding.UTF8.GetString(RSACryptography.Decrypt(CiphertextData, false)); using (MemoryStream CrypStream = new MemoryStream(CiphertextData)) using (MemoryStream PlaiStream = new MemoryStream()) { Byte[] Buffer = new Byte[MaxBlockSize]; int BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize); while (BlockSize > 0) { Byte[] ToDecrypt = new Byte[BlockSize]; Array.Copy(Buffer, 0, ToDecrypt, 0, BlockSize); Byte[] Plaintext = RSACryptography.Decrypt(ToDecrypt, false); PlaiStream.Write(Plaintext, 0, Plaintext.Length); BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize); } return Encoding.UTF8.GetString(PlaiStream.ToArray()); } } }