c#DES加密无法按预期工作

时间:2017-11-01 04:12:54

标签: c# oracle encryption des

以前我们在Oracle中有DES加密功能,现在我们想把它转移到C#代码。但是,在测试这两种方法时,它们会使用相同的输入文本和键给出不同的输出。我注意到在Oracle代码中,它将chr(0)添加到字符串的末尾,而在C#中,我使用new byte [] {0,0}作为相同的内容,不确定这是否会导致问题?

Oracle代码:

create or replace 
function
encrypt_des(p_text varchar2, p_key varchar2) return varchar2 is
v_text varchar2(4000);
v_enc varchar2(4000);
raw_input RAW(128) ;
key_input RAW(128) ;
decrypted_raw RAW(2048);
begin
v_text := rpad( p_text, (trunc(length(p_text)/8)+1)*8, chr(0));
raw_input := UTL_RAW.CAST_TO_RAW(v_text);
key_input := UTL_RAW.CAST_TO_RAW(p_key);
 dbms_output.put_line(raw_input ); 
//display the raw_input

dbms_obfuscation_toolkit.DESEncrypt(input => raw_input,key => 
key_input,encrypted_data =>decrypted_raw);
v_enc := rawtohex(decrypted_raw);

dbms_output.put_line(v_enc);

return v_enc;
end;

C#代码:

        byte[] rgbKey = Encoding.ASCII.GetBytes("aaaaaaaa".Substring(0, 8));

        byte[] inputByteArray = Encoding.UTF8.GetBytes("9804ff20");
        var newbyte = inputByteArray.Concat(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }).ToArray();
        var rawinput= BitConverter.ToString(newbyte).Replace("-", "");
    //display the raw_input

        DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
        dCSP.Mode = CipherMode.ECB;
        dCSP.Padding = PaddingMode.None;
        dCSP.Key = rgbKey;
        MemoryStream mStream = new MemoryStream();
        CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(), CryptoStreamMode.Write);
        cStream.Write(newbyte, 0, newbyte.Length);
        cStream.FlushFinalBlock();
        StringBuilder builder = new StringBuilder();

        foreach (byte num in mStream.ToArray())
        {
            builder.AppendFormat("{0:X2}", num);
        }
        mStream.Close();
        var result= builder.ToString(); 

在加密之前,我比较了两种方法中的raw_input(我在代码中注释的那一行),它们完全相同,但加密后,为什么我会得到不同的结果?

测试结果:

Input text: 9804ff20
Key: aaaaaaaa
Oracle Raw input:39383034666632300000000000000000
C# raw input: 39383034666632300000000000000000
Oracle result: 29B63290034C40DAEF7A5D9608CC19B1
C# result: 29B63290034C40DA5FF660CB09F83313

0 个答案:

没有答案