473,740 Members | 9,506 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

converting python to c# .net

2 New Member
Hi I have a very limited understanding of Python and have given this the best shot i have but still have not been able to get it working.
Is there anyone that knows how to get this into a .net assembly?

Expand|Select|Wrap|Line Numbers
  1. _________________________________________________________
  2. def encrypt_password(challenge, password):
  3.     if challenge['algorithm'] == 'md5':
  4.         inner = md5(challenge['salt'] + password).hexdigest()
  5.     elif challenge['algorithm'] == 'sha1':
  6.         inner = sha(challenge['salt'] + password).hexdigest()
  7.     else:
  8.         raise NotImplementedError(
  9.             "Password encryption algorithm '%s' not implemented." %
  10.             challenge['algorithm'])
  11.     return md5(inner + challenge['nonce']).hexdigest()
  12. _________________________________________________________
This is my attempt at this:

Expand|Select|Wrap|Line Numbers
  1. _________________________________________________________
  2.  
  3.         public static String GetEncryptedPassword(String password, String username)
  4.         {
  5.             INoncesChallengeUser proxyNoncesChallengeUser = XmlRpcProxyGen.Create<INoncesChallengeUser>();
  6.             XmlRpcStruct NoncesChallengeUser = proxyNoncesChallengeUser.GetNoncesChallengeUser(username);
  7.  
  8.             StringBuilder s = new StringBuilder();
  9.             String nonce = (String)NoncesChallengeUser["nonce"];
  10.             String salt = (String)NoncesChallengeUser["salt"];
  11.             String algorithm = (String)NoncesChallengeUser["algorithm"];
  12.  
  13.             byte[] nonceBytes = new byte[nonce.Length];
  14.             byte[] saltBytes = new byte[salt.Length];
  15.             byte[] passwordBytes = new byte[password.Length];
  16.             byte[] algorithmBytes = new byte[salt.Length + password.Length];
  17.             byte[] InnerBytes;
  18.  
  19.             saltBytes = Encoding.UTF8.GetBytes(salt);
  20.             passwordBytes = Encoding.UTF8.GetBytes(password);
  21.             nonceBytes = Encoding.UTF8.GetBytes(nonce);
  22.  
  23.             //Copy password bytes into resulting array
  24.             for (int i = 0; i < passwordBytes.Length; i++)
  25.                 algorithmBytes[i] = passwordBytes[i];
  26.  
  27.             //Append salt bytes to the resulting array.
  28.             for (int i = 0; i < saltBytes.Length; i++)
  29.                 algorithmBytes[saltBytes.Length + i] = saltBytes[i];
  30.  
  31.             switch (algorithm.ToUpper())
  32.             {
  33.                 case "SHA1":
  34.                     //String encrypted_password = md5(sha1(salt + password) + nonce);
  35.                     SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
  36.                     InnerBytes = sha1.ComputeHash(algorithmBytes);
  37.                     break;
  38.  
  39.                 default: //MD5
  40.                     //String encrypted_password = md5(sha1(salt + password) + nonce);
  41.                     MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
  42.                     InnerBytes = md5.ComputeHash(algorithmBytes);
  43.                     break;
  44.             }
  45.  
  46.             //Create finalEncryptedPassword array
  47.             byte[] encryptedPasswordBytes = new byte[InnerBytes.Length + nonceBytes.Length];
  48.  
  49.             //Copy inner bytes into resulting array
  50.             for (int i = 0; i < InnerBytes.Length; i++)
  51.                 encryptedPasswordBytes[i] = InnerBytes[i];
  52.  
  53.             //Append nonce bytes to the resulting array.
  54.             for (int i = 0; i < nonceBytes.Length; i++)
  55.                 encryptedPasswordBytes[InnerBytes.Length + i] = nonceBytes[i];
  56.  
  57.             //Now do the final md5 Encryption
  58.             byte[] finalEncryptedPasswordBytes = new byte[32];
  59.             MD5CryptoServiceProvider md5Final = new MD5CryptoServiceProvider();
  60.             finalEncryptedPasswordBytes = md5Final.ComputeHash(encryptedPasswordBytes);
  61.  
  62.             foreach (byte b in finalEncryptedPasswordBytes)
  63.             {
  64.                 s.Append(b.ToString("x2").ToLower());
  65.             }
  66.             return s.ToString();
  67.         }
  68. _________________________________________________________
Mar 12 '09 #1
6 8397
tlhintoq
3,525 Recognized Expert Specialist
Looks like the long way around to me.
If all you're looking to do is encode a password or some other text maybe this will help get you on your way.

Expand|Select|Wrap|Line Numbers
  1. using System.Security;
  2. using System.Security.Cryptography;
  3. using System.Globalization;
  4.  
  5.         public static string EncodePassword(string originalPassword)
  6.         {
  7.             //Declarations
  8.             Byte[] originalBytes;
  9.             Byte[] encodedBytes;
  10.             MD5 md5;
  11.  
  12.             //Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
  13.             md5 = new MD5CryptoServiceProvider();
  14.             originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
  15.             encodedBytes = md5.ComputeHash(originalBytes);
  16.  
  17.             //Convert encoded bytes back to a 'readable' string
  18.             return BitConverter.ToString(encodedBytes);
  19.         }
  20.  
  21.  
Mar 12 '09 #2
ogtheterror
2 New Member
Thanks for your speedy response, I've revised the code and yes its way neater but i still don't seem to be getting the correct response.

Expand|Select|Wrap|Line Numbers
  1.         public static String GetEncryptedPassword(String password, String username)
  2.         {
  3.             INoncesChallengeUser proxyNoncesChallengeUser = XmlRpcProxyGen.Create<INoncesChallengeUser>();
  4.             XmlRpcStruct NoncesChallengeUser = proxyNoncesChallengeUser.GetNoncesChallengeUser(username);
  5.  
  6.             String nonce = (String)NoncesChallengeUser["nonce"];
  7.             String salt = (String)NoncesChallengeUser["salt"];
  8.             String algorithm = (String)NoncesChallengeUser["algorithm"];
  9.             String inner;
  10.             String final;
  11.  
  12.             //encrypted_password = md5(sha1(salt + password) + nonce);
  13.             if (algorithm.ToUpper() == "SHA1")
  14.                 inner = Sha1EncodePassword(salt + password);
  15.             else
  16.                 inner = Md5EncodePassword(salt + password);
  17.  
  18.             final = Md5EncodePassword(inner + nonce);
  19.             return final;
  20.         }
  21.  
  22.         private static string Md5EncodePassword(string originalPassword)
  23.         {
  24.             //Declarations
  25.             Byte[] originalBytes;
  26.             Byte[] encodedBytes;
  27.             MD5 md5;
  28.  
  29.             //Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
  30.             md5 = new MD5CryptoServiceProvider();
  31.             originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
  32.             encodedBytes = md5.ComputeHash(originalBytes);
  33.  
  34.             //Convert encoded bytes back to a 'readable' string
  35.             return BitConverter.ToString(encodedBytes).ToLower();
  36.         }
  37.  
  38.         private static string Sha1EncodePassword(string originalPassword)
  39.         {
  40.             //Declarations
  41.             Byte[] originalBytes;
  42.             Byte[] encodedBytes;
  43.             SHA1 sha1;
  44.  
  45.             //Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
  46.             sha1 = new SHA1CryptoServiceProvider();
  47.             originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
  48.             encodedBytes = sha1.ComputeHash(originalBytes);
  49.  
  50.             //Convert encoded bytes back to a 'readable' string
  51.             return BitConverter.ToString(encodedBytes).ToLower();
  52.         }
Mar 13 '09 #3
bvdet
2,851 Recognized Expert Moderator Specialist
ogtheterror

In the future, please use code tags when posting code.

posting guidelines

-BV
Moderator
Mar 13 '09 #4
tlhintoq
3,525 Recognized Expert Specialist
Thanks for your speedy response, I've revised the code and yes its way neater but i still don't seem to be getting the correct response.
Feel free to expand on that... What *are* you getting and in what way is it not what you were expecting? Are you getting errors, crashes, or just not what you thought you would get and how?
Mar 13 '09 #5
toanmh
4 New Member
Hi all!
I'm looking in google found some code in python to unwrap package in oracle. But I don't know it.Some one help me to convert it to C# or Java. Please.
Thanks.!

Expand|Select|Wrap|Line Numbers
  1. import re
  2. import base64
  3. import zlib
  4. import sys
  5.  
  6. # simple substitution table
  7. charmap = [0x3d, 0x65, 0x85, 0xb3, 0x18, 0xdb, 0xe2, 0x87, 0xf1, 0x52, 0xab, 0x63, 0x4b, 0xb5, 0xa0, 0x5f, 0x7d, 0x68, 0x7b, 0x9b, 0x24, 0xc2, 0x28, 0x67, 0x8a, 0xde, 0xa4, 0x26, 0x1e, 0x03, 0xeb, 0x17, 0x6f, 0x34, 0x3e, 0x7a, 0x3f, 0xd2, 0xa9, 0x6a, 0x0f, 0xe9, 0x35, 0x56, 0x1f, 0xb1, 0x4d, 0x10, 0x78, 0xd9, 0x75, 0xf6, 0xbc, 0x41, 0x04, 0x81, 0x61, 0x06, 0xf9, 0xad, 0xd6, 0xd5, 0x29, 0x7e, 0x86, 0x9e, 0x79, 0xe5, 0x05, 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b, 0xf7, 0xce]
  8.  
  9. def decode_base64_package(base64str):
  10.     base64dec = base64.b64decode(base64str)[20:] # we strip the first 20 chars (SHA1 hash, I don't bother checking it at the moment)
  11.     decoded = ''
  12.     for byte in range(0, len(base64dec)):
  13.         decoded += chr(charmap[ord(base64dec[byte])])
  14.     return zlib.decompress(decoded)
  15.  
  16.  
  17. sys.stderr.write("=== Oracle 10g/11g PL/SQL unwrapper - by Niels Teusink - blog.teusink.net ===\n\n" )
  18. if len(sys.argv) < 2:
  19.     sys.stderr.write("Usage: %s infile.plb [outfile]\n" % sys.argv[0])
  20.     sys.exit(1)
  21.  
  22. infile = open(sys.argv[1])
  23. outfile = None
  24. if len(sys.argv) == 3:
  25.     outfile = open(sys.argv[2], 'w')
  26.  
  27. lines = infile.readlines()
  28. if outfile:
  29. for i in range(0, len(lines)):
  30.     # this is really naive parsing, but works on every package I've thrown at it
  31.     matches = re.compile(r"^[0-9a-f]+ ([0-9a-f]+)$").match(lines[i])
  32.     if matches:
  33.         base64len = int(matches.groups()[0], 16)
  34.         #print matches.groups()[0]
  35.         base64str = ''
  36.         j = 0
  37.         #print base64len
  38.         while len(base64str) < base64len:
  39.             j+=1
  40.             base64str += lines[i+j]
  41.             #print j
  42.         base64str = base64str.replace("\n","")
  43.  
  44.         if outfile:
  45.             outfile.write(decode_base64_package(base64str) + "\n")
  46.         else:
  47.             print decode_base64_package(base64str)
  48. print "Unwrap is successfully!"
  49.  
  50.  
Jun 29 '10 #6
hitmanjd
3 New Member
@toanmh
hello all, migrate the python code to IronPython, but I have problems with the zlib library, there is no way to load the program.
Anyone know how I can load this library.
Jul 25 '10 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

8
2927
by: Robert Oschler | last post by:
Has anybody seen a Python module that will take an XML document (not a colossal one), and convert it to a Python nested class object? I'm basically looking for something that would allow me to parse an XML document (not tokenize it like SAX or make it into an XPath accessible DOM object like others), directly into a nested Python object so I could access everything through Python class attribute references. Thanks. -- Robert
5
2176
by: Mothra | last post by:
Hi All, I am the current author of the Astro-Sunrise perl module http://search.cpan.org/~rkhill/Astro-Sunrise-0.91/Sunrise.pm and was wondering if it would be worth while to convert it to python. First off, I have never programmed in python. I would like to use this project to learn python. I was wondering if there was a "How to program python for perl programmers" Kinda like what is different between the two, pitfalls for perl...
4
2366
by: eight02645999 | last post by:
hi i need help with converting a piece of perl code to python ...... my $start = '\'; my $file = '\'; my $end = '\'; ..... while(<FILE>) #open a file {
3
4941
by: bolly | last post by:
Hi, I've been putting Python data into a sqlite3 database as tuples but when I retrieve them they come back as unicode data e.g 'u(1,2,3,4)'.How can I change it back to a tuple so I can use it as a Python native datatype? I have looked in the docs and seen there is a decode/encode method but how do I do this? Hope you can help.
5
4589
by: metaperl.etc | last post by:
The following program does not work if you uncomment #lis = + list(args) Evidently Python is opting for the nullary constructor list() as opposed to the other one which takes a sequence. But no newcomer would know this. And the Python docs dont give a good example of dealing with taking a sequence of args and converting it to a list. I must've spent 40 minutes looking through my ora books, googling and irc'ing in vane on this.
5
5169
by: melv | last post by:
Hello, this is my first message sent to the python-list, so forgive any irregularities. is it possible to convert MSword docs into PDF format? i told my future employer that i could, because i knew of the COM scripting abilites that activePython had. and i knew there was modules for PDF creation such as reportlabs.
11
1578
by: Louis.Soninhu | last post by:
Hi pals I have a list like this mylist= I'd like to remove the first and the last item as they are irrevalent, and convert it to the dict: {'tom':'boss','mike':'manager','paul':'employee'}
11
3904
by: Keith Hughitt | last post by:
Hi, I am having a little trouble figuring out how to convert a python datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would like to create a UTC date so that when I send it to MySQL (which treats all dates at local dates by default), it will already have incorporated the proper UTC offset. I've tried looking through the docs http://python.active-venture.com/lib/datetime-datetime.html), but have not had any luck.
0
3348
by: Terry Reedy | last post by:
A. Joseph wrote: These are number representation systems that can be applied to or used with integral, rational (numberator,denominator), and 'point' numbers. Try Wikipedia or any search engine. There are standard algorithms for converting between representations. See above. Good programmer calculators have these built in.
0
8794
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9272
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9211
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8218
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6756
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4572
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3286
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2748
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2195
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.