Hallo,
ich habe folgenden Python-Schnippsel:
def encrypt_dfsId(self,dfsId):
byte1 = bytearray('3go8&$8*3*3h0k(2)2')
byte2 = bytearray(str(dfsId))
byte1_len = len(byte1)
for i in xrange(len(byte2)):
byte2[i] = byte2[i]^byte1[i%byte1_len]
m = md5.new()
m.update(byte2)
result = m.digest().encode('base64')[:-1]
result = result.replace('/', '_')
result = result.replace('+', '-')
return result
Dabei wird aus einem normalen string (dfsId) ein "encoded" string generiert. Das würde ich gerne in C# übersetzen.
Ich bin schon soweit, weiß jedoch auch nicht ob das bis dort alles so richtig ist:
string id = "1312816883569641";
byte[] byte1 = GetBytes("3go8&$8*3*3h0k(2)2");
byte[] byte2 = GetBytes(id);
int byte1_length = byte1.Length;
for(int i =0; i< byte2.Length;i++)
byte2[i] = Convert.ToByte(byte2[i]^byte1[i%byte1_length]);
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
string result= Convert.ToBase64String(md5.ComputeHash(byte2));
result= result.Replace('/', '_');
result = result.Replace('+', '-');
MessageBox.Show(result);
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
Problem ist nun folgendes: Für id = 1312816883569641 bekomme ich result = lhMT967uxSWQvq_eZwkc3Q== heraus. Herauskommen soll aber: result = gF7_aEyB9rj6_N2NQ7ShYA==
Was mache ich falsch? Ich weiß, dass das hier kein Python-Forum ist, aber vlt. fällt ja doch jemandem was auf. Oder gibt es andere Möglichkeiten das in C# zu übersetzen?
Vielen Dank im Voraus!
Installiere dir doch IronPython, gib den Code ein und Debugge ihn Schritt für Schritt.
Evtl siehst du dann den Unterschied.
Ich würde mal drauf tippen, das du vergessen hast das sizeof(char) in .net ==2 ist, während es in Python 1 ist.
Auch bin ich mir sicher das bei Python ein anderer Zeichensatz benutzt wird.
Evtl wäre dann ein Ascii.GetBytes oder UTF8.GetBytes oder was auch immer besser als dein GetBytes
Hi UZI,
FZelle hat Recht, du verwendest ein unterschiedliches Encoding in beiden Snippets.
Da bei Python dem Aufruf von "bytearray()" kein Encoding mitgegeben wurde, muss hier das 1-Byte Encoding zum Zuge kommen.
Bei .NET kommt durch Verwendung von ToCharArray und dem BlockCopy aber ein 2-Byte encoding zustande.
Du musst also explizit über die Encoding-Funktionen sicherstellen, dass du auch 1 Byte pro Character nutzt, beispielsweise mit dem ASCII-Encoding:
static byte[] GetBytes(string str)
{
return Encoding.ASCII.GetBytes(str);
}
Dann kommt auch exakt das selbe heraus.
beste Grüße
zommi