X509证书帮助类

类X509CertificatesHelper是我用来调用证书加解密的帮助类,贴出来希望对大家有用!
X509CertificatesHelper
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

namespace SSO.X509Certificates
{
    
/// <summary>
    
/// 证书帮助类
    
/// </summary>
    public class X509CertificatesHelper
    {
        
#region 变量属性
        
public static readonly X509CertificatesHelper Instance = new X509CertificatesHelper();

        
private const int BUFFER_SIZE = 4*1024;

        
//The identity provider's certificate file name - must be in the application directory.
        private const string idpCertificateFileName = @"App_Data/Cer/SSO.pfx";

        
//The identity provider's certificate/private key file password.
        private const string idpPassword = "password";

        
//The service provider's certificate file name - must be in the application directory.
        private const string spCertificateFileName = @"App_Data/Cer/SSO.cer";

        
//The application key to the identity provider's certificate.
        private const string IdPX509Certificate = "idpX509Certificate";

        
//The application key to the service provider's certificate.
        private const string SPX509Certificate = "spX509Certificate";

        
// Load the IdP certificate
        private string idpfileName = string.Empty;

        
private string spfileName = string.Empty;

        
private X509Certificate2 cert_pfx;
        
private X509Certificate2 cert_cer;

        
/// <summary>
        
/// 获取带密钥的证书
        
/// </summary>
        public X509Certificate2 Cert_Pfx
        {
            
get { return this.cert_pfx; }
        }

        
/// <summary>
        
/// 获取带公钥的证书
        
/// </summary>
        public X509Certificate2 Cert_Cer
        {
            
get { return this.cert_cer; }
        }
        
#endregion

        
#region 私有构造函数
        
private X509CertificatesHelper()
        {
            
this.idpfileName = FileSystemIOProxy.FileSystemIO.CombinePath(FileSystemIOProxy.AppPhysicalPath, idpCertificateFileName);
            
this.spfileName = FileSystemIOProxy.FileSystemIO.CombinePath(FileSystemIOProxy.AppPhysicalPath, spCertificateFileName);

            
this.cert_pfx = LoadCertificate(idpfileName, idpPassword);
            
this.cert_cer = LoadCertificate(spfileName, null);
        }
        
#endregion

        
#region 加载证书文件
        
//Loads the certificate from file.
        
//A password is only required if the file contains a private key.
        
//The machine key set is specified so the certificate is accessible to the IIS process.
        private X509Certificate2 LoadCertificate(string fileName, string password)
        {
            
if ( !File.Exists(fileName) )
            {
                
throw new ArgumentException(
                    
"The certificate file " + fileName + " doesn't exist."
                    );
            }

            
try
            {
                
return new X509Certificate2(fileName, password, X509KeyStorageFlags.UserKeySet);
            }
            
catch (Exception ex)
            {
                
throw new ArgumentException(
                    
"The certificate file " + fileName + " couldn't be loaded - " + ex.Message
                    );
            }
        }
        
#endregion

        
#region 加密

        
/// <summary>
        
/// 加密
        
/// </summary>
        
/// <param name="source">明文</param>
        
/// <returns></returns>
        public byte[] EncryptToByteArray(string source)
        {
            
return EncryptToByteArray(Encoding.UTF8.GetBytes(source));
        }

        
/// <summary>
        
/// 加密
        
/// </summary>
        
/// <param name="source">明文</param>
        
/// <returns></returns>
        public string EncryptToString(byte[] source)
        {
            
return Convert.ToBase64String(EncryptToByteArray(source));
        }

        
/// <summary>
        
/// 加密
        
/// </summary>
        
/// <param name="source">明文</param>
        
/// <returns></returns>
        public string EncryptToString(string source)
        {
            
return Convert.ToBase64String(EncryptToByteArray(Encoding.UTF8.GetBytes(source)));
        }

        
/// <summary>
        
/// 加密
        
/// </summary>
        
/// <param name="source">明文</param>
        
/// <returns></returns>
        public byte[] EncryptToByteArray(byte[] source)
        {
            
byte[] str_out;

            
using (MemoryStream fin = new MemoryStream(source),fout = new MemoryStream() )
            {
                
long lSize = fin.Length; // 输入文件长度 
                int size = (int)lSize;
                
byte[] bytes = new byte[BUFFER_SIZE]; // 缓存 
                int read = -1// 输入文件读取数量 

                
byte[] key;//密钥 
                byte[] iv;//初始向量 
                byte[] ctkey;//以密文形式存在的密钥 
                byte[] ctiv;//以密文形式存在的初始向量 

                SymmetricAlgorithm sma 
= Rijndael.Create();
                sma.GenerateKey();
                sma.GenerateIV();

                key 
= sma.Key;
                iv 
= sma.IV;

                
//加密用cer证书提取公钥即可 
                RSACryptoServiceProvider crypto_enc = (RSACryptoServiceProvider)cert_cer.PublicKey.Key;
                ctkey 
= crypto_enc.Encrypt(key, false);
                ctiv 
= crypto_enc.Encrypt(iv, false);

                BinaryWriter bb 
= new BinaryWriter(fout, Encoding.UTF8);
                
long kl = (long)ctkey.Length;
                
long il = (long)ctiv.Length;

                
//写入密钥和向量长度
                bb.Write(kl);
                bb.Write(il);

                
//写入密钥和向量内容
                fout.Write(ctkey, 0, (int)kl);
                fout.Write(ctiv, 
0, (int)il);
                
                
using (CryptoStream cout = new CryptoStream(fout, sma.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    BinaryWriter bw 
= new BinaryWriter(fout, Encoding.UTF8);

                    
//写入原文长度
                    bw.Write(lSize);

                    
//写入原文加密后文本(将数据流链接到加密转换的流)
                    while ((read = fin.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        cout.Write(bytes, 
0, read);
                        cout.FlushFinalBlock();
                    }

                    cout.Flush();

                    str_out 
= fout.ToArray();
                    

                    cout.Close();
                }
            }

            
return str_out;
        }
        
#endregion

        
#region 解密

        
/// <summary>
        
/// 解密
        
/// </summary>
        
/// <param name="source">密文</param>
        
/// <returns></returns>
        public byte[] DecrytpToByteArray(string source)
        {
            
return DecrytpToByteArray(Convert.FromBase64String(source));
        }

        
/// <summary>
        
/// 解密
        
/// </summary>
        
/// <param name="source">密文</param>
        
/// <returns></returns>
        public string DecrytpToString(byte[] source)
        {
            
return Encoding.UTF8.GetString(DecrytpToByteArray(source));
        }

        
/// <summary>
        
/// 解密
        
/// </summary>
        
/// <param name="source">密文</param>
        
/// <returns></returns>
        public string DecrytpToString(string source)
        {
            
return Encoding.UTF8.GetString(DecrytpToByteArray(Convert.FromBase64String(source)));
        }

        
/// <summary>
        
/// 解密
        
/// </summary>
        
/// <param name="source">密文</param>
        
/// <returns></returns>
        public byte[] DecrytpToByteArray(byte[] source)
        {
            
byte[] str_out;

            
using (MemoryStream fin = new MemoryStream(source), fout = new MemoryStream())
            {
                
int size = (int)fin.Length;
                
byte[] bytes = new byte[BUFFER_SIZE];
                
int read = -1;
                
int value = 0;
                
int outValue = 0;

                BinaryReader bb 
= new BinaryReader(fin, Encoding.UTF8);
                
long kl = bb.ReadInt64();
                
long il = bb.ReadInt64();

                
byte[] ctkey = new byte[kl];
                
byte[] ctiv = new byte[il];

                fin.Read(ctkey, 
0, (int)kl);
                fin.Read(ctiv, 
0, (int)il);

                
//解密需要从pfx证书中提取私钥 
                RSACryptoServiceProvider crypto_dec = (RSACryptoServiceProvider)cert_pfx.PrivateKey;
                
byte[] ptkey = crypto_dec.Decrypt(ctkey, false);
                
byte[] ptiv = crypto_dec.Decrypt(ctiv, false);

                SymmetricAlgorithm sma 
= SymmetricAlgorithm.Create();
                sma.Key 
= ptkey;
                sma.IV 
= ptiv;

                value 
= 32;
                
long lSize = 0;

                
using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read))
                {

                    BinaryReader br 
= new BinaryReader(fin, Encoding.UTF8); 
                    lSize 
= br.ReadInt64(); 

                    
long numReads = lSize / BUFFER_SIZE; 

                    
long slack = (long)lSize % BUFFER_SIZE; 

                    
for (int i = 0; i < numReads; ++i) 
                    { 
                        read 
= cin.Read(bytes, 0, bytes.Length); 
                        fout.Write(bytes, 
0, read); 
                        value 
+= read; 
                        outValue 
+= read; 
                    } 

                    
if (slack > 0
                    { 
                        read 
= cin.Read(bytes, 0, (int)slack); 
                        fout.Write(bytes, 
0, read); 
                        value 
+= read; 
                        outValue 
+= read; 
                    }

                    fout.Flush();

                    str_out 
= fout.ToArray();

                    fout.Close();
                }

                
//比较加密前的长度和解密后的长度
                if (outValue != lSize)
                {
                    
return null;
                }
                
else
                {
                    
return str_out;
                }
            }
        }
        
#endregion
    }
}

 

posted @ 2010-08-11 16:01  遥望星空  阅读(579)  评论(0编辑  收藏  举报