跨平台加密/解密(C#/ Android)

时间:2018-11-29 10:30:57

标签: java c# android .net encryption

我有点陷入困境,这是场景。我们有一个现有的C#应用​​程序,该应用程序使用以下功能对数据进行加密。

private static readonly byte[] iv = new byte[] { 97, 190, 45, 87, 145, 210, 157, 160 };

public static String EncVal(String valueToEncrypt)
  {
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            des.IV = new byte[8];
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(iv, new byte[0]);
            des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]);
            MemoryStream ms = new MemoryStream(valueToEncrypt.Length * 2);
            CryptoStream encStream = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            byte[] plainBytes = Encoding.UTF8.GetBytes(valueToEncrypt);
            encStream.Write(plainBytes, 0, plainBytes.Length);
            encStream.FlushFinalBlock();
            byte[] encryptedBytes = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(encryptedBytes, 0, (int)ms.Length);
            encStream.Close();
            return Convert.ToBase64String(encryptedBytes);
   }

我这样称呼

static void Main(string[] args)
{
    string name = "Test";
    string nameEncrypted = Cryptography.EncVal(name);
    //I get bfq0D2qnaRc=
}

现在我想在Android中解密该值

以下是我正在使用的功能

private static final byte[] IV =  new byte[] { 97, (byte)190, 45, 87, (byte)145, (byte)210, (byte)157, (byte)160 };
private static final byte[] key = new byte[] {(byte)213,(byte)219,66,(byte)134,(byte)252,60,114,37,(byte)176,(byte)237,(byte)137,(byte)137,34,(byte)174,94,(byte)132};


public static void main(String[] args) {
        // TODO Auto-generated method stub

        String decyptedValue = DecodeString("bfq0D2qnaRc="); //=>should get Test, but getting exception here 

//
//javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
//  


    }



    public static String DecodeString(String input)
            {
            try
            {
                Cipher c = Cipher.getInstance("RC2/CBC/PKCS5Padding");


                c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "RC2"), new RC2ParameterSpec(key.length*8, IV, 0));

                byte[] decrypted = c.doFinal(Base64.getDecoder().decode(input));
                return new String(decrypted, "UTF-8");
            }
            catch(Exception exp)
            {
                System.out.println(exp.getMessage());
            }
            return "";


}

我正在跟踪异常javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.

有什么主意吗?请注意,我们无法更改C#代码,唯一的选择是实施Android / Java代码。

0 个答案:

没有答案