deepmap123
deepmap123
2015-03-06 03:41
采纳率: 100%
浏览 2.4k
已采纳

C# des算法转java des 结果不一致

C#
其中
provider.Mode加密为CBC
provider.Padding为PKCS7

  string data="-1";
    byte[] rgbKey = {69, 70, 67, 49, 56, 49, 69, 70};
  byte[] rgbIV = {54, 57, 51, 69, 52, 48, 55, 70};
  MemoryStream ms = new MemoryStream();
            CryptoStream encStream = new CryptoStream(ms, provider.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter(encStream);
            sw.Write(data);
            sw.Flush();
            encStream.FlushFinalBlock();
            sw.Flush();            
            byte[] bufferb = ms.ToArray();
            String buffer = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

算出来的buffer值rLrYBUc04hM=,
bufferb
[0] 172 byte
[1] 186 byte
[2] 216 byte
[3] 5 byte
[4] 71 byte
[5] 52 byte
[6] 226 byte
[7] 19 byte

下面为我转为java的代码,3个变量值同上面

 public static String encrypt(String data,byte[] rgbKey, byte[] rgbIV) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(rgbKey);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(rgbIV);
        AlgorithmParameterSpec paramSpec = iv;
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
        byte[] datadd=data.getBytes("ASCII");
        byte[] bytes = cipher.doFinal(datadd);
    return new String(bytes,"ASCII");       
    }

算出来的结果是���G4�,bytes为[-84, -70, -40, 5, 71, 52, -30, 19]

java结果是错的。

求大神帮查看下java哪里地方写错了,谢谢。

java最后一句改成
return Base64.encodeBase64String(bytes);
就和C#一致

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • danielinbiti
    danielinbiti 2015-03-06 04:31
    已采纳

    编码方式不一致。就是手机和PC机用java加密出来的还不一致呢。
    把数据转换成base64编码后再做加密解密。

    点赞 评论

相关推荐