c#开发前端时调用java开发的接口,需要数据加密后通讯。两边都需要同时通过DES(BASE64)进行加解密。
代码如下
c#端:
加密
public static String Encrypt(String toEncrypt, String key) { Byte[] _Key = Encoding.ASCII.GetBytes(key); Byte[] _Source = Encoding.UTF8.GetBytes(toEncrypt); DES des = DES.Create("DES"); des.Mode = CipherMode.ECB; des.Padding = PaddingMode.PKCS7; des.Key = _Key; ICryptoTransform cTransform = des.CreateEncryptor(); Byte[] cryptData = cTransform.TransformFinalBlock(_Source, 0, _Source.Length); String CryptString = Convert.ToBase64String(cryptData); return CryptString; }
解密
public static String Decrypt(string encryptedSource, string key) { Byte[] _Key = Encoding.ASCII.GetBytes(key); DES des = DES.Create("DES"); des.Mode = CipherMode.ECB; des.Padding = PaddingMode.PKCS7; des.Key = _Key; ICryptoTransform cTransform = des.CreateDecryptor(); Byte[] encryptedData = Convert.FromBase64String(encryptedSource); Byte[] originalSrouceData = cTransform.TransformFinalBlock(encryptedData, 0, encryptedData.Length); String originalString = Encoding.UTF8.GetString(originalSrouceData); return originalString; }
Java端:
加密
public static String encrypt(String data,String key) throws Exception { byte[] bt = encrypt(data.getBytes(), key.getBytes()); String strs = (new BASE64Encoder()).encode(bt); return strs; }
private static byte[] encrypt(byte[] data, byte[] key) throws Exception { SecureRandom sr = new SecureRandom(); DESKeySpec dks = new DESKeySpec(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES"); cipher.init(1, securekey, sr); return cipher.doFinal(data); }
解密:
public static String decrypt(String data,String key) throws IOException, Exception { if (data == null) { return null; } else { BASE64Decoder decoder = new BASE64Decoder(); byte[] buf = decoder.decodeBuffer(data); byte[] bt = decrypt(buf, key.getBytes()); return new String(bt); } } private static byte[] decrypt(byte[] data, byte[] key) throws Exception { SecureRandom sr = new SecureRandom(); DESKeySpec dks = new DESKeySpec(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES"); cipher.init(2, securekey, sr); return cipher.doFinal(data); }