JAVA和c# 之间数据通讯时通过DES进行加密解密

1 篇文章 0 订阅

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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值