0

我正在使用代码对 c# 中的数据进行 Base-64 编码和加密,然后将文件发送到我的 Android 应用程序,在那里我尝试对其进行解密。

问题是,我得到一个“Base64 编码输入字符串的长度不是 4 的倍数”。解密时出错:

(Android 的 Java 代码):

    try
    {
          Boolean inEvent = false;

          // read encrypted file to string
          BufferedInputStream fin = new BufferedInputStream(new FileInputStream(filename));
          ByteArrayOutputStream bout = new ByteArrayOutputStream();
          byte buffer[] = new byte[8192];
          int read = fin.read(buffer);
          while(read != -1) {
              bout.write(buffer, 0, read);
              read = fin.read(buffer);
          }
          fin.close();
          String encryptedText = bout.toByteArray().toString();
          String unencryptedText = "";

          // decrypt string
          try
          {
              unencryptedText = Decrypt(encryptedText, sKey); <-- error occurs here
          }
          catch ( Exception e)
          {
              alert(e.getMessage());
              return sched;
          }

解密方法:

protected String Decrypt(String text, String key) throws Exception
{
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
    byte[] keyBytes= new byte[16];
    byte[] b= key.getBytes("UTF-8");
    int len= b.length;
    if (len > keyBytes.length) len = keyBytes.length;
    System.arraycopy(b, 0, keyBytes, 0, len);
    SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
    cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec);

    byte [] results = cipher.doFinal(Base64Coder.decode(text));
    return new String(results,"UTF-8");
}

最后,这是我用来加密的 c# 代码:

(c#代码):

  string Encrypt(string textToEncrypt, string key)
  {
    RijndaelManaged rijndaelCipher = new RijndaelManaged();
    rijndaelCipher.Mode = CipherMode.CBC;
    rijndaelCipher.Padding = PaddingMode.PKCS7;

    rijndaelCipher.KeySize = 0x80;
    rijndaelCipher.BlockSize = 0x80;
    byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
    byte[] keyBytes = new byte[0x10];
    int len = pwdBytes.Length;
    if (len > keyBytes.Length)
    {
      len = keyBytes.Length;
    }
    Array.Copy(pwdBytes, keyBytes, len);
    rijndaelCipher.Key = keyBytes;
    rijndaelCipher.IV = keyBytes;
    ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
    byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
    return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0,   plainText.Length));
  }

不知道出了什么问题。密钥的长度是否必须是某个特定的字节数?

4

1 回答 1

2

评论已经确定了问题,如果您在此处调试关键项目,您会立即看到它:您认为您正在阅读的 base 64 字符串。

您从bout. 但是您尝试将其转换为字符串表示并没有像您想象的那样做任何事情。它将类似于“[B@2352544e]”,只是toString()数组中 Java 的内部默认值。相反,尝试new String(bout.toByteArray(), Charset.forName("US-ASCII")).

于 2012-12-16T12:04:46.527 回答