C#和Java中的加密/解密

时间:2013-09-09 14:04:39

标签: c# java android .net encryption

我想在Android上用Java解密我的加密字符串。

使用以下代码我在C#中加密了我的原始字符串:

        public static string Encrypt(string decryptedString)
    {
        DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
        desProvider.Mode = CipherMode.ECB;
        desProvider.Padding = PaddingMode.PKCS7;
        desProvider.Key = Encoding.ASCII.GetBytes("password");
        using (MemoryStream stream = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(stream, desProvider.CreateEncryptor(), CryptoStreamMode.Write))
            {
                byte[] data = Encoding.Default.GetBytes(decryptedString);
                cs.Write(data, 0, data.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(stream.ToArray());
            }
        }
    }

我试图用Java解密它:

   public String decrypt(){
       String keyStr = "password";
       String msg = "KGFL1GG5VLQ=";
       String erg = "";
       try{


       KeySpec ks = new DESKeySpec(keyStr.getBytes("UTF-8"));
       SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(ks);
       IvParameterSpec iv = new IvParameterSpec(Hex.decodeHex("1234567890ABCDEF".toCharArray()));
       Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
       cipher.init(Cipher.DECRYPT_MODE, key, iv);

       byte[] decoded = cipher.doFinal(Base64.decodeBase64(msg));
       erg = new String(decoded);
       } catch (Exception e){
           erg = "error";
       }
       return erg;

   }

我使用commons-codec-1.8.jar。它崩溃时出现以下错误:

W/dalvikvm(17859): VFY: unable to resolve static method 339: Lorg/apache/commons/codec/binary/Base64;.decodeBase64 (Ljava/lang/String;)[B

请指出我出错的地方。

1 个答案:

答案 0 :(得分:0)

我认为这个问题类似于:

NoSuchMethodError using commonc codec in Android application

Apache Commons Codec with Android: could not find method

答案是,Android使用的是apache commons的1.2版本。