62,074
社区成员
发帖
与我相关
我的任务
分享
/** */
private static String characterSet = "UTF-8";
/** */
private static String keyMode = "DES/CBC/PKCS5Padding";
/** */
private static String encAlg = "DES";
public static byte[] encrypt(String message, String key) throws Exception {
//生成一个实现指定转换的 Cipher对象 ,
//"DES/CBC/PKCS5Padding" 算法名称/反馈模式/填充方案
Cipher cipher = Cipher.getInstance(keyMode);
//创建一个 DESKeySpec 对象,使用 key 中的前 8 个字节作为 DES 密钥的密钥内容
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(characterSet));
//生成“DES”密钥算法的 SecretKeyFactory 对象。
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encAlg);
//根据提供的密钥算法类型,生成 SecretKey 对象。
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
//初始化IV制定字符集
IvParameterSpec iv = new IvParameterSpec(key.getBytes(characterSet));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return cipher.doFinal(message.getBytes(characterSet));
}
public static String hexByteArrToString(byte b[]) {
StringBuffer str = new StringBuffer();
for (int i = 0; i < b.length; i++) {
//以十六进制的无符号整数形式返回一个整数参数的字符串
String hexStr = Integer.toHexString(0xff & b[i]);
if (hexStr.length() < 2){
hexStr = "0" + hexStr;
}
str.append(hexStr);
}
return str.toString();
}
public static String getEncStr(String key,String value) throws Exception{
//String str = URLEncoder.encode(value, "utf-8").toLowerCase();//小写加密
//制定加密字符串的字符集
String str = URLEncoder.encode(value, characterSet);
byte[] encryptByteArr = encrypt(str, key);
String encStr = hexByteArrToString(encryptByteArr).toUpperCase();
return encStr;
}
public static void main(String[] args) throws Exception {
System.out.println("请输入需要加密的数据 : ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String input = null;
try {
input = br.readLine();
System.out.println("您输入的加密数据为: " + input);
} catch (IOException e) {
e.printStackTrace();
}
String encstr = getEncStr("datacvg1",input);
System.out.println("加密后的 密文是 : " + encstr);
}
/**
以上java 加密代码,想转换成c#代码,其中有一些Helper辅助类不知道有影响吗(Cipher 如果可以写死,就写死)
*/
/*c#代码如下,但是加密的串不一样,请高手赐教*/
/*
加密内容: guoyaokonggu
加密后的密文是 : 837FFC37E620BDE149362B9872643ECC(java加密后的密文)
约定加密key:sinokey0
*/
public string EncryptDES2(string encryptString, string encryptKey)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
byte[] rgbIV = Encoding.UTF8.GetBytes("UTF-8");
//byte[] rgbIV = Keys;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
dCSP.Mode = CipherMode.CBC;
dCSP.Padding = PaddingMode.PKCS7;
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
byte[] res = mStream.ToArray();
foreach (byte b in res)
ret.AppendFormat("{0:x2}", b);
return ret.ToString().ToUpper();
}
catch
{
return encryptString;
}
}