C#加密算法
一、MD5加密
/// <summary> /// MD5_16位加密 /// </summary> public static string GetMD5_16(string value) { string md5Str = string.Empty; MD5 md5 = new MD5CryptoServiceProvider(); byte[] byData = Encoding.Default.GetBytes(value); byte[] result = md5.ComputeHash(byData); md5Str = BitConverter.ToString(result, 4, 8); md5Str = md5Str.Replace("-", ""); return md5Str; }
/// <summary> /// MD5_32位加密 /// </summary> public static string GetMD5_32(string value) { string md5Str = string.Empty; MD5 md5 = new MD5CryptoServiceProvider(); byte[] byData = Encoding.Default.GetBytes(value); byte[] result = md5.ComputeHash(byData); md5Str = BitConverter.ToString(result); md5Str = md5Str.Replace("-", ""); return md5Str; }
/// <summary> /// MD5_Base64加密 /// </summary> public static string GetMD5_Base64(string value) { string md5Str = string.Empty; MD5 md5 = new MD5CryptoServiceProvider(); byte[] byData = Encoding.Default.GetBytes(value); byte[] result = md5.ComputeHash(byData); md5Str = Convert.ToBase64String(result); return md5Str; }
二、AES加密
public static string AESEncode(string encryptKey, string encryptString) { var _keyByte = Encoding.UTF8.GetBytes(encryptKey); var _valueByte = Encoding.UTF8.GetBytes(encryptString); using (var aes = new RijndaelManaged()) { aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; aes.Key = _keyByte; var cryptoTransform = aes.CreateEncryptor(); var resultArray = cryptoTransform.TransformFinalBlock(_valueByte, 0, _valueByte.Length); return Convert.ToBase64String(resultArray); } }
public static string AESEncode(string encryptKey, string encryptString) { byte[] toEncryptArray = Encoding.UTF8.GetBytes(encryptString); byte[] seed = Encoding.UTF8.GetBytes(encryptKey); using (var aesProvider = new AesCryptoServiceProvider()) { aesProvider.Key = seed; aesProvider.Mode = CipherMode.ECB; aesProvider.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = aesProvider.CreateEncryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return ToHexString(resultArray); //return Convert.ToBase64String(results); } }
public static string ToHexString(byte[] buf) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < buf.Length; i++) { string hex = buf[i].ToString("X2"); if (hex.Length == 1) { hex = '0' + hex; } sb.Append(hex.ToUpper()); } return sb.ToString(); }
三、AES解密
public static string AesDecrypt(string encryptKey, string encryptString) { var _keyByte = Encoding.UTF8.GetBytes(encryptKey); var _valueByte = Convert.FromBase64String(encryptString); using (var aes = new RijndaelManaged()) { aes.Key = _keyByte; aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; var cryptoTransform = aes.CreateDecryptor(); var resultArray = cryptoTransform.TransformFinalBlock(_valueByte, 0, _valueByte.Length); return Encoding.UTF8.GetString(resultArray); } }
四、DES加密
public static string DESEncrypt(string encryptKey, string encryptString) { byte[] toEncryptArray = Encoding.UTF8.GetBytes(encryptString); byte[] seed = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); using (var desProvider = new DESCryptoServiceProvider()) { desProvider.Key = seed; desProvider.Mode = CipherMode.ECB; desProvider.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = desProvider.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); //return ToHexString(resultArray); return Convert.ToBase64String(resultArray); } }
public static string DESDecrypt(string decryptString, string decryptKey, string iv) {byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8)); byte[] rgbIV = Encoding.UTF8.GetBytes(iv); byte[] inputByteArray = Convert.FromBase64String(decryptString); DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); dCSP.Mode = CipherMode.CBC; dCSP.Padding = PaddingMode.PKCS7; MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Encoding.UTF8.GetString(mStream.ToArray()); } }
五、SHA256加密
public string GetSHA256hash(string input) { byte[] clearBytes = Encoding.UTF8.GetBytes(input); SHA256 sha256 = new SHA256Managed(); sha256.ComputeHash(clearBytes); byte[] hashedBytes = sha256.Hash; sha256.Clear(); string output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower(); return output; }
六、AES-256随机加密密钥
public static string GenAES256Key() { AesCryptoServiceProvider key = new AesCryptoServiceProvider(); key.KeySize = 256; key.GenerateKey(); return Convert.ToBase64String(key.Key); }
七、RSA 加密
public static string EncryptData(string content, string encryptKey, string charset) { RSACryptoServiceProvider rsa = DecodePemPublicKey(encryptKey); byte[] cipherBytes = rsa.Encrypt(Encoding.GetEncoding(charset).GetBytes(content), false); return Convert.ToBase64String(cipherBytes); }
private static RSACryptoServiceProvider DecodePemPublicKey(string pemstr) { byte[] pkcs8publickkey; pkcs8publickkey = Convert.FromBase64String(pemstr); if (pkcs8publickkey != null) { RSACryptoServiceProvider rsa = DecodeRSAPublicKey(pkcs8publickkey); return rsa; } return null; } private static RSACryptoServiceProvider DecodeRSAPublicKey(byte[] publickey) { // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" byte[] SeqOID = {0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00}; byte[] seq = new byte[15]; // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------ MemoryStream mem = new MemoryStream(publickey); BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading byte bt; ushort twobytes; try { twobytes = binr.ReadUInt16(); if (twobytes == 0x8130 ) //data read as little endian order (actual data order for Sequence is 30 81) binr.ReadByte(); //advance 1 byte else if (twobytes == 0x8230) binr.ReadInt16(); //advance 2 bytes else return null; seq = binr.ReadBytes(15); //read the Sequence OID if (!CompareBytearrays(seq, SeqOID)) //make sure Sequence for OID is correct return null; twobytes = binr.ReadUInt16(); if (twobytes == 0x8103 ) //data read as little endian order (actual data order for Bit string is 03 81) binr.ReadByte(); //advance 1 byte else if (twobytes == 0x8203) binr.ReadInt16(); //advance 2 bytes else return null; bt = binr.ReadByte(); if (bt != 0x00) //expect null byte next return null; twobytes = binr.ReadUInt16(); if (twobytes == 0x8130 ) //data read as little endian order (actual data order for Sequence is 30 81) binr.ReadByte(); //advance 1 byte else if (twobytes == 0x8230) binr.ReadInt16(); //advance 2 bytes else return null; twobytes = binr.ReadUInt16(); byte lowbyte = 0x00; byte highbyte = 0x00; if (twobytes == 0x8102 ) //data read as little endian order (actual data order for Integer is 02 81) lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus else if (twobytes == 0x8202) { highbyte = binr.ReadByte(); //advance 2 bytes lowbyte = binr.ReadByte(); } else return null; byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order int modsize = BitConverter.ToInt32(modint, 0); byte firstbyte = binr.ReadByte(); binr.BaseStream.Seek(-1, SeekOrigin.Current); if (firstbyte == 0x00) { //if first byte (highest order) of modulus is zero, don't include it binr.ReadByte(); //skip this null byte modsize -= 1; //reduce modulus buffer size by 1 } byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data return null; int expbytes = (int)binr .ReadByte(); // should only need one byte for actual exponent data (for all useful values) byte[] exponent = binr.ReadBytes(expbytes); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAKeyInfo = new RSAParameters(); RSAKeyInfo.Modulus = modulus; RSAKeyInfo.Exponent = exponent; RSA.ImportParameters(RSAKeyInfo); return RSA; } catch (Exception) { return null; } finally { binr.Close(); } } private static bool CompareBytearrays(byte[] a, byte[] b) { if (a.Length != b.Length) return false; int i = 0; foreach (byte c in a) { if (c != b[i]) return false; i++; } return true; }
八、Base64加密
//加密
public static string Base64Encrypt(string str) { byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str); return Convert.ToBase64String(encbuff); }
//解密 public static string Base64Decrypt(string str) { byte[] decbuff = Convert.FromBase64String(str); return System.Text.Encoding.UTF8.GetString(decbuff); }
九、签名
public static String Sign(String content, String signType, String privateKey, String charset, String password, String signAlgorithm) { if (signType.equals("CA")) { infosecapiLib.infosec icbcCA = new infosecapiLib.infosec(); return icbcCA.sign_SHA1(content, privateKey, password); } else if (signType.equals("RSA")) { if (signAlgorithm.equals("MD5WithRSA")) { return RSAClass.RSAFromPkcs8.signMD5withRSA(content, privateKey, "GBK"); } else { return RSAClass.RSAFromPkcs8.sign(content, privateKey, "UTF-8"); } } else if (signType.equals("RSA2")) { return RSAClass.RSAFromPkcs8.signWithRSASHA256(content, privateKey, "UTF-8"); } return null; }