110,539
社区成员
发帖
与我相关
我的任务
分享
private static String CHATSET="UTF-8" ;
//加密
public static String desEncrypt(String input, String keystr) throws Exception {
try {
byte[] datasource = input.getBytes(CHATSET);
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(keystr.getBytes((CHATSET)));
//创建一个密匙工厂,然后用它把DESKeySpec转换成
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
//Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance("DES");
//用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
//现在,获取数据并加密
//正式执行加密操作
return new sun.misc.BASE64Encoder().encode(cipher.doFinal(datasource)) ;
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
C#代码:
using System.Security.Cryptography;
using System.IO;
// des加密函数
public string Encrypt(string pToEncrypt, string sKey)
{
// 创建des加密没
using (DESCryptoServiceProvider des = newDESCryptoServiceProvider())
{
// 得到UTF-8的数据源
byte[] inputByteArray =Encoding.UTF8.GetBytes(pToEncrypt);
// 设置key和iv密钥
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
//由于java是使用默认加密模式,C#默认是CBC,需要修改为ECB
des.Mode =CipherMode.ECB;
// 创建数据流并进行加密
MemoryStream ms = new MemoryStream();
using (CryptoStream cs = new CryptoStream(ms,des.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
}
// 关闭数据流
ms.Close();
return Convert.ToBase64String(ms.ToArray());
}
}
DESKeySpec(byte[] key)
Creates a DESKeySpec object using the first 8 bytes in key as the key material for the DES key.
DESKeySpec(byte[] key, int offset)
Creates a DESKeySpec object using the first 8 bytes in key, beginning at offset inclusive, as the key material for the DES key.