关于c#:Base-64 char数组或字符串的长度无效

Invalid length for a Base-64 char array or string

这是我的加密和解密方法。我有两个数据库,我将加密密码从一个数据库复制到另一个数据库。代码是用VB编写的,但我把它转换成了C。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Security.Cryptography;
 using System.IO;
 namespace AccountSystem.Class{
class ClEncrDecr
{
    private TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider();

    private byte[] TruncateHash(string key, int length)
    {
        SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
        //Hash the Key
        byte[] keyBytes = System.Text.Encoding.Unicode.GetBytes(key);
        byte[] hash = sha1.ComputeHash(keyBytes);

        // truncate or pad the hash
        Array.Resize(ref hash, length);
        return hash;
    }

    public ClEncrDecr()
    {
        string key ="ABCD";
        tripleDESCryptoServiceProvider.Key = TruncateHash(key, tripleDESCryptoServiceProvider.KeySize / 8 );
        tripleDESCryptoServiceProvider.IV = TruncateHash("", tripleDESCryptoServiceProvider.BlockSize / 8 );
    }

    public string EncryptData(string plainText)
    {
        byte[] plaintextBytes = System.Text.Encoding.Unicode.GetBytes(plainText);
        MemoryStream ms = new MemoryStream();
        CryptoStream encStream = new CryptoStream(ms, tripleDESCryptoServiceProvider.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
        encStream.Write(plaintextBytes, 0, plaintextBytes.Length);
        encStream.FlushFinalBlock();
        return Convert.ToBase64String(ms.ToArray());
    }

    public string DecryptData(string encryptedtext)
    {
        byte[] encryptedBytes = Convert.FromBase64String(encryptedtext);
        MemoryStream ms = new MemoryStream();
        CryptoStream decStream = new CryptoStream(ms, tripleDESCryptoServiceProvider.CreateDecryptor(), CryptoStreamMode.Write);
        decStream.Write(encryptedBytes, 0, encryptedBytes.Length);
        decStream.FlushFinalBlock();
        return System.Text.Encoding.Unicode.GetString(ms.ToArray());
    }
}
}

登录代码:

1
MessageBox.Show(crypto.DecryptData(obj.password))

当我们调用DecryptData(string encryptedtext)时,它抛出了一个例外,说Invalid length for a Base-64 char array or string。我能做什么?


如果你encrypted have the following密码:P></

dfghfgdfgd667878nnvghv

恩我不能从base64转换到字节阵列,因为它base64string not a valid。有效的base64string摇篮:P></

dfghfgdfgd667878nnvghv==


as the Claudio在上述评论,你encryptedtext is not base64编码的字符串变量,也许是至少填充字符(S missing at the end)。P></

这是not visible from the example but how这created,你可能想知道的问题:for example这个面貌如何decode base64的编码和字符串?P></

关于填充:http:///wiki/en.wikipedia.org Base64 #填充P></