Getting different encryption results between C#.Net and Oracle

♀尐吖头ヾ 提交于 2019-12-24 15:06:27

问题


I want to encrypt some strings based on SHA1 algorithm in both C#.Net and Oracle 10g.

My algorithm in C#.Net:

string salt = "123";
System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create();
byte[] preHash = System.Text.Encoding.UTF32.GetBytes(salt);
byte[] hash = sha.ComputeHash(preHash);

string password = System.Convert.ToBase64String(hash);
password = password.Substring(0, 8);

// password value is: "7yP7/lkJ"

In Oracle:

Create Or Replace Function Sha1(P_Value Varchar2,P_Length Number) Return Varchar2 
Is 
P_String Varchar2(2000) := P_Value ;
L_Hash_Value_Raw    Raw (100);    
Lv_Hash_Value_Varchar   Varchar2 (40); 
Begin   
    L_Hash_Value_Raw := Dbms_Crypto.Hash (Src   => Utl_Raw.Cast_To_Raw(P_String),       
                                         Typ   => Dbms_Crypto.Hash_Sh1);   
-- Convert Into Varchar2 
Select   Utl_Raw.Cast_To_Varchar2(Utl_Encode.Base64_Encode(L_Hash_Value_Raw))
Into   Lv_Hash_Value_Varchar  
From   Dual;  
    Lv_Hash_Value_Varchar := Substr(Lv_Hash_Value_Varchar,0,P_Length);
Return Lv_Hash_Value_Varchar;
End;

Oracle's invokation:

select SHA1('123', 8) from dual; -- Result: "QLOAFWMI"

Maybe my general question is what is the difference between Oracle (PL/SQL) and .Net regarding encryption/raw/hex levels? I guess that answer would solve this specific problem.


回答1:


you use wrong encoding. try the following code:

string salt = "123";
System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create();
byte[] preHash = System.Text.Encoding.UTF8.GetBytes(salt);
byte[] hash = sha.ComputeHash(preHash);

string password = System.Convert.ToBase64String(hash);
password = password.Substring(0, 8);


来源:https://stackoverflow.com/questions/10469633/getting-different-encryption-results-between-c-net-and-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!