在C#中使用Triple DES加密,在perl中解密

时间:2017-06-07 16:14:36

标签: c# perl encryption

我正在尝试使用triple des加密C#中的一串文本。最终需要使用perl解密文本。从另一端出来的文字仍然看起来像gobblygyk。我在密码上错过了一面旗帜吗?

C#encrypt:

    public static string EncryptString(string str)
    {
        using (var provider = new TripleDESCryptoServiceProvider())
        {
            provider.Mode = CipherMode.CBC;

            provider.Key = Encoding.ASCII.GetBytes("THISIS24BYTESWORTHOFTEXT");
            provider.IV = Encoding.ASCII.GetBytes("01234567");
            provider.Padding = PaddingMode.PKCS7;

            var hashBytes = EncryptStringToBytes(str, provider);

            return Convert.ToBase64String(hashBytes);  
        }
    }

    private static byte[] EncryptStringToBytes(string txt, TripleDESCryptoServiceProvider desAlg)
    {

        var encryptor = desAlg.CreateEncryptor(desAlg.Key, desAlg.IV);

        using (var msEncrypt = new MemoryStream())
        {
            using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                using (var swEncrypt = new StreamWriter(csEncrypt))
                {
                    swEncrypt.Write(txt);
                }
            }
            return msEncrypt.ToArray();
        }
    }
}

perl decrypt:

sub DecryptString { 
my ($dbh, $args) = @_;

my $inargs = $args->{INPUT};
my $key="THISIS24BYTESWORTHOFTEXT";
my $iv = "01234567";

my $cipher = Crypt::CBC->new(
        -cipher => 'DES_EDE3',
        -key => $key,
        -literal_key => 1,
        -iv => $iv,
        -add_header => 0,
        -keysize => 24,
);

return $cipher->decrypt($inargs);
}

1 个答案:

答案 0 :(得分:0)

解密前需要解码。根据下面的评论,我将呼叫改为

$ inargs = decode_base64($ inargs);

在致电解密之前。