对方给的加密方法:java
/**
* 3DES加密
*
* @param src
* @param key
* @return
* @throws Exception
*/
public static String desedeEncoder(String src, String key) throws Exception {
SecretKey secretKey = new SecretKeySpec(build3DesKey(key), "DESede");
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] b = cipher.doFinal(src.getBytes("UTF-8"));
return byte2HexStr(b);
}
build3DesKey方法是构建24位密钥,byte2HexStr是用来返回大写的16进制的字符串。
/**
* 构造3DES加解密方法key
*
* @param keyStr
* @return
* @throws Exception
*/
private static byte[] build3DesKey(String keyStr) throws Exception {
byte[] key = new byte[24];
byte[] temp = keyStr.getBytes("UTF-8");
if (key.length > temp.length) {
System.arraycopy(temp, 0, key, 0, temp.length);
} else {
System.arraycopy(temp, 0, key, 0, key.length);
}
return key;
}
/**
* 字节数组转化为大写16进制字符串
*
* @param b
* @return
*/
private static String byte2HexStr(byte[] b) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++) {
String s = Integer.toHexString(b[i] & 0xFF);
if (s.length() == 1) {
sb.append("0");
}
sb.append(s.toUpperCase());
}
return sb.toString();
}
对于java我不是很熟悉,
第一个问题就是:这里java的模式是ECB,填充方式为PKCS5Padding吗?
第二个问题:若java是ECB的,那么c#中也应该是ECB模式,填充方式应该是什么?(C#的模式有:ANSIX923、ISO10126、None、PKCS7、Zero,而Java有:NoPadding、PKCS5Padding、SSL3Padding)
我在c#里用的加密方法是(ECB,Zero填充方式):
public string Encrypt3DES(string a_strString, string a_strKey)
{
TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
DES.Key = build3DesKey("a_strKey");
DES.Mode = CipherMode.ECB;
DES.Padding = System.Security.Cryptography.PaddingMode.Zeros;
ICryptoTransform DESEncrypt = DES.CreateEncryptor();
byte[] Buffer = System.Text.Encoding.UTF8.GetBytes(a_strString);
return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
}
构建KEy方法;
private byte[] build3DesKey(string keyStr) {
byte[] key = new byte[24];
byte[] temp = System.Text.Encoding.UTF8.GetBytes(keyStr);
if (key.Length > temp.Length) {
for (int i = 0; i < temp.Length;i++ )