473,386 Members | 1,715 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

converting python to c# .net

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 8350
tlhintoq
3,525 Expert 2GB
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
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 Expert Mod 2GB
ogtheterror

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

posting guidelines

-BV
Moderator
Mar 13 '09 #4
tlhintoq
3,525 Expert 2GB
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
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, 0xba, 0x84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 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
@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
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...
5
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...
4
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
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...
5
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....
5
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...
11
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
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...
0
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...

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.