C#加密核心代码:
//密钥
private const string sKey = "A3F2569DESJEIWBCJOTY45DYQWF68H1Y";
//矢量,矢量可以为空
private const string sIV = "qcDY6X+aPLw=";
//构造一个对称算法
private SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
#region public string EncryptString(string Value)
/// 加密字符串
/// 输入的字符串
/// 加密后的字符串
public string EncryptString(string Value)
{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
mCSP.Key = Convert.FromBase64String(sKey);
mCSP.IV = Convert.FromBase64String(sIV);
//指定加密的运算模式
mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
//获取或设置加密算法的填充模式
mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
byt = Encoding.UTF8.GetBytes(Value);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
JAVA解密核心代码:
// 把密钥参数转为byte数组
public byte[] dBase64(String parm) throws IOException {
BASE64Decoder dec = new BASE64Decoder();
byte[] dnParm = dec.decodeBuffer(parm);
return dnParm;
}
/**
* 对 Byte 数组进行解密
* @param buff
* 要解密的数据
* @return 返回加密后的 String
*/
public static String createDecryptor(byte[] buff)
throws NoSuchPaddingException, NoSuchAlgorithmException,
UnsupportedEncodingException {
try {
c.init(Cipher.DECRYPT_MODE, deskey);// 初始化密码器,用密钥deskey,进入解密模式
cipherByte = c.doFinal(buff);
} catch (java.security.InvalidKeyException ex) {
ex.printStackTrace();
} catch (javax.crypto.BadPaddingException ex) {
ex.printStackTrace();
} catch (javax.crypto.IllegalBlockSizeException ex) {
ex.printStackTrace();
}
return (new String(cipherByte, "UTF-8"));
}
public void getKey(String key) throws IOException, InvalidKeyException,
InvalidKeySpecException {
byte[] dKey = dBase64(key);
try {
deskey = new javax.crypto.spec.SecretKeySpec(dKey, Algorithm);
c = Cipher.getInstance(Algorithm);
} catch (NoSuchPaddingException ex) {
} catch (NoSuchAlgorithmException ex) {
}
}