最近做项目接触了一些关于用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()); } } }