1.對稱加密算法
對稱加密是最快速、最簡單的一種加密方式,加密(encryption)與解密(decryption)用的是同樣的密鑰(secret key)。
對稱加密有很多種算法,由於它效率很高,所以被廣泛使用在很多加密協議的核心當中。對稱加密通常使用的是相對較小的密鑰,
一般小於256 bit。因為密鑰越大,加密越強,但加密與解密的過程越慢。如果你只用1 bit來做這個密鑰,那黑客們可以先試着用0來解密,
不行的話就再用1解;但如果你的密鑰有1 MB大,黑客們可能永遠也無法破解,但加密和解密的過程要花費很長的時間。
密鑰的大小既要照顧到安全性,也要照顧到效率,是一個trade-off。
常用對稱加密:DES、3DES、AES等
(代碼后續添加)
2.非對稱加密算法
非對稱加密為數據的加密與解密提供了一個非常安全的方法,它使用了一對密鑰,公鑰(public key)和私鑰(private key)。
私鑰只能由一方安全保管,不能外泄,而公鑰則可以發給任何請求它的人。非對稱加密使用這對密鑰中的一個進行加密,而解密則需要另一個密鑰。
比如,你向銀行請求公鑰,銀行將公鑰發給你,你使用公鑰對消息加密,那么只有私鑰的持有人--銀行才能對你的消息解密。
與對稱加密不同的是,銀行不需要將私鑰通過網絡發送出去,因此安全性大大提高。
常用非對稱加密:DSA、RSA等
目前C#中提供的RSA非對稱加密(其他語言如JAVA是可以逆向加解密的,但沒有測試過),只能使用公鑰進行加密,只能使用私鑰進行解密,不能逆向使用(私鑰無法加密,公鑰無法解密),
因為這樣的安全性更高,不會出現私鑰加密后的數據,所有公鑰持有者都可以解密的問題,如果一定要有這種需求出現,則可以使用
第三方的加解密組件BouncyCastle來實現
//引入命名空間
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
//RSA測試實例
string oldData = "taiyonghai";
CreateRSAKey();
string ciphertext = RSAEncrypt(oldData);
string newData = RSADecrypt(ciphertext);
/// <summary>
/// 創建RSA公鑰私鑰
/// </summary>
public void CreateRSAKey()
{
//設置[公鑰私鑰]文件路徑
string privateKeyPath = @"d:\\PrivateKey.xml";
string publicKeyPath = @"d:\\PublicKey.xml";
//創建RSA對象
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
//生成RSA[公鑰私鑰]
string privateKey = rsa.ToXmlString(true);
string publicKey = rsa.ToXmlString(false);
//將密鑰寫入指定路徑
File.WriteAllText(privateKeyPath, privateKey);//文件內包含公鑰和私鑰
File.WriteAllText(publicKeyPath, publicKey);//文件內只包含公鑰
}
/// <summary>
/// 使用RSA實現加密
/// </summary>
/// <param name="data">加密數據</param>
/// <returns></returns>
public string RSAEncrypt(string data)
{
//C#默認只能使用[公鑰]進行加密(想使用[公鑰解密]可使用第三方組件BouncyCastle來實現)
string publicKeyPath = @"d:\\PublicKey.xml";
string publicKey = File.ReadAllText(publicKeyPath);
//創建RSA對象並載入[公鑰]
RSACryptoServiceProvider rsaPublic = new RSACryptoServiceProvider();
rsaPublic.FromXmlString(publicKey);
//對數據進行加密
byte[] publicValue = rsaPublic.Encrypt(Encoding.UTF8.GetBytes(data), false);
string publicStr = Convert.ToBase64String(publicValue);//使用Base64將byte轉換為string
return publicStr;
}
/// <summary>
/// 使用RSA實現解密
/// </summary>
/// <param name="data">解密數據</param>
/// <returns></returns>
public string RSADecrypt(string data)
{
//C#默認只能使用[私鑰]進行解密(想使用[私鑰加密]可使用第三方組件BouncyCastle來實現)
string privateKeyPath = @"d:\\PrivateKey.xml";
string privateKey = File.ReadAllText(privateKeyPath);
//創建RSA對象並載入[私鑰]
RSACryptoServiceProvider rsaPrivate = new RSACryptoServiceProvider();
rsaPrivate.FromXmlString(privateKey);
//對數據進行解密
byte[] privateValue = rsaPrivate.Decrypt(Convert.FromBase64String(data), false);//使用Base64將string轉換為byte
string privateStr = Encoding.UTF8.GetString(privateValue);
return privateStr;
}
附錄:
在線加解密站點:http://web.chacuo.net/netrsakeypair

