aes c# java_AES加密,C#和java相同
///
///用种子获取密钥字节///
/// 密钥种子
/// 编码格式
/// 密钥长度(一般为16,不清楚时不要随意动)
///
public static byte[] GetKeyBySeed(string strKey, Encoding encoding, int nLen = 16)
{byte[] bySeed =encoding.GetBytes(strKey);byte[] byKeyArray = null;using (var st = newSHA1CryptoServiceProvider())
{using (var nd = newSHA1CryptoServiceProvider())
{var rd =nd.ComputeHash(st.ComputeHash(bySeed));
byKeyArray=rd.Take(nLen).ToArray();
}
}returnbyKeyArray;
}///
///加密 参数:string///
/// 加密内容
/// 密钥字节数组
/// 向量(注意目前只研究支持16位长度)
/// 编码方式
/// string:密文
public static string Encrypt(string strCon, byte[] byteKey, Encoding encoding)
{try{if (string.IsNullOrWhiteSpace(strCon))
{return null;
}byte[] byCon =encoding.GetBytes(strCon);var rm = newRijndaelManaged
{
Key=byteKey,
Mode=CipherMode.ECB,
Padding=PaddingMode.PKCS7
};
ICryptoTransform cTransform=rm.CreateEncryptor();byte[] resultArray = cTransform.TransformFinalBlock(byCon, 0, byCon.Length);returnProgram.ByteArrayToHexString(resultArray);
}catch{return "";
}
}public static string Decrypt(string strCon, byte[] byteKey,Encoding encoding)
{try{if (string.IsNullOrWhiteSpace(strCon))
{return null;
}byte[] byCon =HexStrToByte(strCon);var rm = newRijndaelManaged
{
Key=byteKey,
Mode=CipherMode.ECB,
Padding=PaddingMode.PKCS7
};
ICryptoTransform cTransform=rm.CreateDecryptor();byte[] resultArray = cTransform.TransformFinalBlock(byCon, 0, byCon.Length);returnencoding.GetString(resultArray);
}catch(Exception ex)
{return "";
}
}///
///
///
///
///
public static byte[] HexStrToByte(stringhexString)
{
hexString= hexString.Replace(" ", "");if ((hexString.Length % 2) != 0)
hexString+= " ";byte[] returnBytes = new byte[hexString.Length / 2];for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i]= Convert.ToByte(hexString.Substring(i * 2, 2), 16);returnreturnBytes;
}///
///转化为16进制///
///
///
public static string ByteArrayToHexString(byte[] data)
{
StringBuilder sb= new StringBuilder(data.Length * 3);foreach (byte b indata)
{
sb.Append(Convert.ToString(b,16).PadLeft(2, '0'));
}returnsb.ToString().ToUpper();
}