Is Jboss 5.1.0 Password Based Encryption Secure? - security

I am securing our our servers using password based encryption for Jboss 5.1.0.
I have read the parts of the RFC:
https://www.rfc-editor.org/rfc/rfc2898
I have read the several Jboss documents several times:
https://docs.jboss.org/jbosssecurity/docs/6.0/security_guide/html/Encrypting_Data_Source_Passwords.html (this is for 6.0, but works with 5.1.0)
Now, let me explain my issue.
In the official JBoss document listed above, they treat "Secured Identity" encryption as if it is secure. Heck, it is in the documents. Worse, I've seen other people ask questions on Stack Overflow on how to use this. This is not secure. To make it secure, one has to write their own encryption class overriding org.jboss.resource.security.SecureIdentityLoginModule.
I was able to prove this by doing a quick google search of "Decrypt Jboss 5.1.0 Password" and the first result was a jar file that decrypted Jboss passwords using the recommended approach in the official Jboss documentation.
Enter Password Based Encryption.
Knowing I've already found a security flaw in the first approach, I am already wearing of taking advice from this documentation-- if your wrong once, your probably wrong twice. However, it seems I don't have I must use approach 2: Password Based Encryption.
My concern is, the documentation makes me generate a 'master.password' file. I am assuming this is the derived key function mentioned in the RFC. However, I don't know for certain.
All in all, my gut tells me this:
Your making me store a master.password on my server. The master.password file that contains the derived key function can be used by some code somewhere to simply decrypt my encrypted password. That is because I am specifying salt and iterations elsewhere in other files.
This whole process seems like a mathematical function. On my end it looks like this:
? = DerivedKeyFunction(Salt, Iterations, Password)
But for the hacker it looks like this:
EncodedPassword = DerivedKeyFunction(Salt, Iterations, ?)
I'm claim to be neither a cryptographer or a Jboss expert, but my gut tells me all a hacker needs to do is look at the Jboss source code (which is open source as far as I know) and do a little bit of reverse engineering to get the password using the server.password file.
So my question is: How secure is Password Based Encryption on Jboss (assuming the hacker gained access to the server)? Has anyone actually looked into this?
------------ EDIT -----------------
To clarify:
This is for JBoss to connect to our Database. This is not for an end-user to log into their user account on a web application.
JBoss uses a master.password (or server.password... its just a filename) which contains some sort of encrypted string. I'm not sure what's in here, its not well documented (or maybe it is and I just don't understand).
After the configuration is followed, a password is never entered again. I don't see how this is secure. I'm guessing I can somehow use the server.password file created in step 1 to decrypt my database password. Someone just hasn't written a convenient jar file yet. But the code is opensource, so I'm guessing the right person knows how to do this very easily.
I am sharing the steps due to the number of terrible setups I've seen people using on stack overflow. The steps are as follows:
From jboss/common/lib folder, Create server.password file. place in server/conf directory.:
java -cp jbosssx.jar org.jboss.security.plugins.FilePassword <8Charactersalt> <iterationsMoreThan1000> <aLongRandomPassword> server.password
#outputs server.password file which contains encrypted string.
Encrypt Database Password
java -cp jbosssx.jar org.jboss.security.plugins.PBEUtils <8Charactersalt> <iterationsMoreThan1000> <aLongRandomPassword> <databaseConnectionPassword>
#outputs encrypted DB Password
Remove Username & Password & Update Datasource XML
<security-domain>EncryptedMySqlDbRealm</security-domain>
<depends>jboss.security:service=JaasSecurityDomain,domain=ServerMasterPassword</depends>
Add Mbean To Datasource XML. it specifies the server.password file, salt and iterations.
{CLASS}org.jboss.security.plugins.FilePassword:${jboss.server.home.dir}/conf/server.password
${8Charactersalt}
${iterationsMoreThan1000}
Add Application Policy To Login Config XML. specify username, encrypted password, and datasource to encrypt. There is a 1 to 1 mapping between application policies and datasources, so if you have two datasources, it appears you need 2 application policies as well. Otherwise you get errors starting up jboss.
${DatabaseUsername}
${EncryptedPassword}
jboss.jca:service=LocalTxCM,name=${DataSourceNameFromDatasourceXML}
jboss.security:service=JaasSecurityDomain,domain=ServerMasterPassword

It sounds like your just want to obfuscate your password. Encrypting it just makes this a circular process: You need to choose a password to encrypt your password that you will use to encrypt your password that you will.....
Simply Base-64 encode it. Or some other type of (non-encrypting) encoding.

First, a cavet: I know nothing of the JBoss system to which you are referring. But I'm fairly sure the system is not asking you to "store a master.password on my server." However, I am familiar enough with encryption to offer this explanation:
You want to store some plain-text data and protect it with a password. So, you ask a user for a password, encrypt it, and store the encrypted text (call this "cipher-text") and then discard the password. When the user wants to retrieve it, you ask for a password and then decrypt the "Cipher-Text". If the password is correct you will get back the original Plain-Text.
An encryption (and decryption) process requires a Key. This is numeric value, not a password. So, you need a way to derive a Key-value from some text Pass-Phrase. The DerivedKeyFunction performs this action. The returned result is not an Encoded Password. It is a Key value that is passed to the encryption/decryption process.
So, you ask the user for a Pass-Phrase, then call DerivedKeyFunction to get a Key-value, then encrypt the Plain-Text into Cipher-Text (using the Key), store the resulting Cipher-Text and then discard the Pass-Phrase and the Key.
And to decrypt, you ask for the Pass-Phrase, re-derive the Key, and then decrypt.
Basically, the DerivedKeyFunction is a Hash function (or process); you use it to "convert" the Pass-Phrase into a numeric value that can be used by the encrypt process.
Now, you will note the other two parameters to the DerivedKeyFunction: "Salt" and "Iterations". These are required to increase the difficulty of an attack on your data. "Iterations" (obviously) specifies the number of times to re-hash the Pass-Phrase. And the "Salt" injects a random number into this iterative process.
Hopefully, you see now that these are two values that you will need to store with the Cipher-Text. Any time you want to derive the Key from your Pass-Phrase, you must do it the same way each time; that means iterating the same number of times and injecting the same "Salt" value.
So, now your process is:
1) Pick a random Salt value (yes, a random number).
2) Decide on iteration count, lets say for example 100,000. (this should be a big number, so DerivedKeyFunction takes a long time; explanation in a moment)
3) Ask the user for a Pass-Phrase.
4) Call DerivedKeyFunction handing it the Pass-Phrase, the random Salt value, and 100,000. This returns a Key-value (implied by those 3 parameters).
5) Encrypt Plain-Text into Cipher-Text using the Key-value.
6) Store the Cipher-Text and the Salt value and the iteration count (100,000)
7) Discard the Pass-Phrase and Key-value.
To decrypt:
1) Ask for the Pass-Phrase.
2) Call DerivedKeyFunction handing it the Pass-Phrase, the stored Salt value, and the stored iteration count. If the Pass-Phrase is correct, then the same (correct) Key-value will be returned.
3) Decrypt the Cipher-Text into Plain-Text using the Key-value.
Ok, so why choose a large number for the iteration count? Well, an attacker is will simply just spin around trying password after password until they successfully decrypt the the Cipher-Text. But they have to call DerivedKeyFunction with each attempt they make. And, they must use the correct Salt value and Iteration count that you used when you encrypted the data. And, yes, since you had to store them for your use, an attacker will know what they are; but they still have to call DerivedKeyFunction over-and-over. So you should see that the higher you make the iteration count, the less the number of attempts-per-second an attacker can try.
Although you didn't mention it, when using CBC (Cipher-Block-Chain) type encryption algorithms, there is another parameter called the IV or Initialization Vector. This value is an input to the encryption/decryption as a companion to the Key. As it pertains to the above processes, treat it as an extension of the Key: The DerivedKeyFunction that is used should provide both a Key-value and an IV-value. And, as with the Key-value, the IV-value is never stored and is discarded at the same points that the Key-value is discarded.

Related

Is there a hashing technique that works both ways?

TLDR;
The hashing function generates a different hash every time for the same piece of data, but it can determine if a particular hash was generated with the piece of data or not.
Eg:
hash_func(xyz): abc123
hash_func(xyz): jhg342 // different hash, even if the data was same.
decode_hash(jhg324) == xyz
This gives true, because the hash function determined that jhg324 is indeed the hash of xyz
The Question
For an Open Source website, I want to store the email in hashed form (because all the users will be public), but the site needs to know if an email was used to register for another account so that it can ensure one account per email.
However, all the emails are from one organization only. This means, they all look exactly like uid#org_name.com. This means anyone can run through all the UIDs and find out which hash belongs to which email, and thus, which person.
Therefore, is there a way to hash the email such that the hash knows which email it belongs to, but hashing the same email does not generate the same hash.
P.S. Please note that I cannot use Salting as the site will be Open Source and the salt will be publicly available.
This doesn't make sense - you're conflating hashing and encryption in a very strange way. What you're describing wouldn't really be a cryptographically secure hash function. By definition, cryptographically secure hash functions are one way. In fact, if you could reverse it, there would be little point to using it at all because it would no longer be secure. This would make it possible to brute-force passwords and would "break" passwords that were used in multiple places.
Also, why would you want it to hash to different values each time? That's what you use a salt for.
If you want to be able to reverse it later, just use an encryption algorithm like AES. Even better, many databases even offer features for securely storing sensitive information; see, for example, SQL Server's Always Encrypted feature.

How does the system know when a password contains parts of a previous password?

Probably a super basic question. I know many online services hash and salt passwords instead of storing them as plaintext for security purposes. My university's web portal requires students to change their passwords every 6 months. From what I know, the system is built on Oracle software.
My question is, however, how does the system know when my 20 character long password (with capitals, numbers, and symbols) contains 3 characters in the same order as the new password I'm trying to set? If the passwords are hashed, shouldn't the algorithm be one-way? Or is it possible that system encrypts the plaintext passwords and stores them? Wouldn't that be less secure?
Sorry if the question is hard to understand. Let me know if you need me to clarify. Thanks in advance!
If you have to enter your previous password when creating a new one, the system can compare them directly. This could even be done client-side.
EDIT
There are only a few other possibilities
They store your password in plaintext (in which case they should fire their entire IT department)
Their encryption method is two-way i.e. it can be decrypted (in which case they should fire their entire IT department)
They temporarily store your password when you log in. Maybe in a cookie or on the server. (In which case they should fire their entire IT department)
It is likely that the prevoius password table is encrypted (possibly using rot26).
The system can only check if the new password matches the old password exactly (compares the hashes). If it's checking substring matches, the passwords are likely being stored in plaintext.
No bueno.
EDIT: Or what Nick said, of course.

Keeping Encrypted Strings Safe with Multiple Encrypts

A system I have been working on for a while requires DPA, and asked a question about keeping the data passcodes safe. I have since them come up with an idea to fix that, which involves having the data decrypt password for the database stored on the database, but have that encrypted with validated users password (which is stored as an MD5 key) after a different type of hashing.
The question is that does encrypting the password multiple times with different keys (at least 20 characters long, with possible extension) make it considerably easier to decrypt without prior knowledge or information on the password?
No, in general a good cipher should have the property that you cannot retrieve data even if you know the plaintext. Having the data encrypted should not have much influence, geven a good cipher and a big enough key space.
First off, MD5 is no longer considered a secure encryption algorithm. See http://www.kb.cert.org/vuls/id/836068 for details.
Secondly, the encryption key for the data should not be stored in the database itself. It should be stored separately. That way there are at least two things that have to be obtained (the database file and the key) to decrypt the data. If the key is stored in the database itself, it probably wouldn't take long to find it once someone has the database file.
Find a separate method for storing the key. It should either be coded into the application or stored in a file that is obfuscated in some way.

How do the password revealers work?

I've seen some password revealing software. Most of them has a shooting pointer like pointer and you can just point the password text box and the software is revealing the password.
But still the protected software and the revealer software are not interconnected. They are separate processes running on the same host.
My queries are,
How does a one process access the other software's information?
What are the limitations of it?
What are the practices that I can use for prevent this?
Edit : Yes, Keeping a password with dummy data is the mostly used solution for this. But still the same theory can be applied to some other case right? As an example an external program can read your emails, A spy program can record your activities etc. And even we can implement some cool features like drag and drop support to IE to Mozilla :)
So in this case the most effective
solution would be a "Blocking"
mechanism. Is there anyway to do this? (Avoid accessing the process's resources???)
As silky said it's just a matter of sending windows messages, there is a very simple source that reveals all password fields at once. A simple countermeasure would be a password field that holds dummy characters instead of the real password. You can capture what is being typed, store it in a variable and replace it with the dummy character in your password field.
Probably by finding the control and sending a message to the textbox that changes the 'password' character to blank (i.e. it will reeval).
So:
By sending windows messages to them
I can't recall, but I'm pretty sure you just need the window handle.
Don't display the password in a password field at all. Just hold it somewhere in memory, and only show it if the user specifically asks for it.
IIRC this "weakness" had been eliminated since about Windows XP SP2? In any case, i'm pretty sure the standard Windows textbox control that is used for passwords got an upgrade so that you couldn't just use tools like Spy++ to peek at the actual text that was being masked.
The way passwords work:
When a password is set the password is converted to a hash value using a hash function, and it is that hash value that is stored. The password is never stored. When a user logs in the password is hashed and compared to the stored hash value. If the two hashes match then the user submitted the correct password.
In order to reveal a password the stored hash value has to be compared to something with a known hash value or, in the case of a broken hash function, the hash value can be guessed into the submitted value. The later of these possibilities is the method used by Cisco password crackers, if you can get into the box, because Cisco uses a notoriously weak hash function. In the case of later Windows OSes the hash function used is NTLM, which is very strong. In this case you must compare the stored hash values to known hash values. This method is called a rainbow table. A typical alpha-numeric and 7-bit ASCII special character 14 character password has a rainbow table that is 64gb large. This is why longer passwords are vastly superior since it will take a few minutes to compare a hash value against billions of other values.

Encrypting/Hashing plain text passwords in database [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
I've inherited a web app that I've just discovered stores over 300,000 usernames/passwords in plain text in a SQL Server database. I realize that this is a Very Bad Thing™.
Knowing that I'll have to update the login and password update processes to encrypt/decrypt, and with the smallest impact on the rest of the system, what would you recommend as the best way to remove the plain text passwords from the database?
Any help is appreciated.
Edit: Sorry if I was unclear, I meant to ask what would be your procedure to encrypt/hash the passwords, not specific encryption/hashing methods.
Should I just:
Make a backup of the DB
Update login/update password code
After hours, go through all records in the users table hashing the password and replacing each one
Test to ensure users can still login/update passwords
I guess my concern is more from the sheer number of users so I want to make sure I'm doing this correctly.
EDIT (2016): use Argon2, scrypt, bcrypt, or PBKDF2, in that order of preference. Use as large a slowdown factor as is feasible for your situation. Use a vetted existing implementation. Make sure you use a proper salt (although the libraries you're using should be making sure of this for you).
When you hash the passwords use DO NOT USE PLAIN MD5.
Use PBKDF2, which basically means using a random salt to prevent rainbow table attacks, and iterating (re-hashing) enough times to slow the hashing down - not so much that your application takes too long, but enough that an attacker brute-forcing a large number of different password will notice
From the document:
Iterate at least 1000 times, preferably more - time your implementation to see how many iterations are feasible for you.
8 bytes (64 bits) of salt are sufficient, and the random doesn't need to be secure (the salt is unencrypted, we're not worried someone will guess it).
A good way to apply the salt when hashing is to use HMAC with your favorite hash algorithm, using the password as the HMAC key and the salt as the text to hash (see this section of the document).
Example implementation in Python, using SHA-256 as the secure hash:
EDIT: as mentioned by Eli Collins this is not a PBKDF2 implementation. You should prefer implementations which stick to the standard, such as PassLib.
from hashlib import sha256
from hmac import HMAC
import random
def random_bytes(num_bytes):
return "".join(chr(random.randrange(256)) for i in xrange(num_bytes))
def pbkdf_sha256(password, salt, iterations):
result = password
for i in xrange(iterations):
result = HMAC(result, salt, sha256).digest() # use HMAC to apply the salt
return result
NUM_ITERATIONS = 5000
def hash_password(plain_password):
salt = random_bytes(8) # 64 bits
hashed_password = pbkdf_sha256(plain_password, salt, NUM_ITERATIONS)
# return the salt and hashed password, encoded in base64 and split with ","
return salt.encode("base64").strip() + "," + hashed_password.encode("base64").strip()
def check_password(saved_password_entry, plain_password):
salt, hashed_password = saved_password_entry.split(",")
salt = salt.decode("base64")
hashed_password = hashed_password.decode("base64")
return hashed_password == pbkdf_sha256(plain_password, salt, NUM_ITERATIONS)
password_entry = hash_password("mysecret")
print password_entry # will print, for example: 8Y1ZO8Y1pi4=,r7Acg5iRiZ/x4QwFLhPMjASESxesoIcdJRSDkqWYfaA=
check_password(password_entry, "mysecret") # returns True
The basic strategy is to use a key derivation function to "hash" the password with some salt. The salt and the hash result are stored in the database. When a user inputs a password, the salt and their input are hashed in the same way and compared to the stored value. If they match, the user is authenticated.
The devil is in the details. First, a lot depends on the hash algorithm that is chosen. A key derivation algorithm like PBKDF2, based on a hash-based message authentication code, makes it "computationally infeasible" to find an input (in this case, a password) that will produce a given output (what an attacker has found in the database).
A pre-computed dictionary attack uses pre-computed index, or dictionary, from hash outputs to passwords. Hashing is slow (or it's supposed to be, anyway), so the attacker hashes all of the likely passwords once, and stores the result indexed in such a way that given a hash, he can lookup a corresponding password. This is a classic tradeoff of space for time. Since password lists can be huge, there are ways to tune the tradeoff (like rainbow tables), so that an attacker can give up a little speed to save a lot of space.
Pre-computation attacks are thwarted by using "cryptographic salt". This is some data that is hashed with the password. It doesn't need to be a secret, it just needs to be unpredictable for a given password. For each value of salt, an attacker would need a new dictionary. If you use one byte of salt, an attacker needs 256 copies of their dictionary, each generated with a different salt. First, he'd use the salt to lookup the correct dictionary, then he'd use the hash output to look up a usable password. But what if you add 4 bytes? Now he needs 4 billion copies of the the dictionary. By using a large enough salt, a dictionary attack is precluded. In practice, 8 to 16 bytes of data from a cryptographic quality random number generator makes a good salt.
With pre-computation off the table, an attacker has compute the hash on each attempt. How long it takes to find a password now depends entirely on how long it takes to hash a candidate. This time is increased by iteration of the hash function. The number iterations is generally a parameter of the key derivation function; today, a lot of mobile devices use 10,000 to 20,000 iterations, while a server might use 100,000 or more. (The bcrypt algorithm uses the term "cost factor", which is a logarithmic measure of the time required.)
I would imagine you will have to add a column to the database for the encrypted password then run a batch job over all records which gets the current password, encrypts it (as others have mentiond a hash like md5 is pretty standard edit: but should not be used on its own - see other answers for good discussions), stores it in the new column and checks it all happened smoothly.
Then you will need to update your front-end to hash the user-entered password at login time and verify that vs the stored hash, rather than checking plaintext-vs-plaintext.
It would seem prudent to me to leave both columns in place for a little while to ensure that nothing hinky has gone on, before eventually removing the plaintext passwords all-together.
Don't forget also that anytime the password is acessed the code will have to change, such as password change / reminder requests. You will of course lose the ability to email out forgotten passwords, but this is no bad thing. You will have to use a password reset system instead.
Edit:
One final point, you might want to consider avoiding the error I made on my first attempt at a test-bed secure login website:
When processing the user password, consider where the hashing takes place. In my case the hash was calculated by the PHP code running on the webserver, but the password was transmitted to the page from the user's machine in plaintext! This was ok(ish) in the environment I was working in, as it was inside an https system anyway (uni network). But, in the real world I imagine you would want to hash the password before it leaves the user system, using javascript etc. and then transmit the hash to your site.
Follow Xan's advice of keeping the current password column around for a while so if things go bad, you can rollback quick-n-easy.
As far as encrypting your passwords:
use a salt
use a hash algorithm that's meant for passwords (ie., - it's slow)
See Thomas Ptacek's Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes for some details.
I think you should do the following:
Create a new column called HASHED_PASSWORD or something similar.
Modify your code so that it checks for both columns.
Gradually migrate passwords from the non-hashed table to the hashed one. For example, when a user logs in, migrate his or her password automatically to the hashed column and remove the unhashed version. All newly registered users will have hashed passwords.
After hours, you can run a script which migrates n users a time
When you have no more unhashed passwords left, you can remove your old password column (you may not be able to do so, depends on the database you are using). Also, you can remove the code to handle the old passwords.
You're done!
As the others mentioned, you don't want to decrypt if you can help it. Standard best practice is to encrypt using a one-way hash, and then when the user logs in hash their password to compare it.
Otherwise you'll have to use a strong encryption to encrypt and then decrypt. I'd only recommend this if the political reasons are strong (for example, your users are used to being able to call the help desk to retrieve their password, and you have strong pressure from the top not to change that). In that case, I'd start with encryption and then start building a business case to move to hashing.
For authentication purposes you should avoid storing the passwords using reversible encryption, i.e. you should only store the password hash and check the hash of the user-supplied password against the hash you have stored. However, that approach has a drawback: it's vulnerable to rainbow table attacks, should an attacker get hold of your password store database.
What you should do is store the hashes of a pre-chosen (and secret) salt value + the password. I.e., concatenate the salt and the password, hash the result, and store this hash. When authenticating, do the same - concatenate your salt value and the user-supplied password, hash, then check for equality. This makes rainbow table attacks unfeasible.
Of course, if the user send passwords across the network (for example, if you're working on a web or client-server application), then you should not send the password in clear text across, so instead of storing hash(salt + password) you should store and check against hash(salt + hash(password)), and have your client pre-hash the user-supplied password and send that one across the network. This protects your user's password as well, should the user (as many do) re-use the same password for multiple purposes.
Encrypt using something like MD5, encode it as a hex string
You need a salt; in your case, the username can be used as the salt (it has to be unique, the username should be the most unique value available ;-)
use the old password field to store the MD5, but tag the MD5 (i.e.g "MD5:687A878....") so that old (plain text) and new (MD5) passwords can co-exist
change the login procedure to verify against the MD5 if there is an MD5, and against the plain password otherwise
change the "change password" and "new user" functions to create MD5'ed passwords only
now you can run the conversion batch job, which might take as long as needed
after the conversion has been run, remove the legacy-support
Step 1: Add encrypted field to database
Step 2: Change code so that when password is changed, it updates both fields but logging in still uses old field.
Step 3: Run script to populate all the new fields.
Step 4: Change code so that logging in uses new field and changing passwords stops updating old field.
Step 5: Remove unencrypted passwords from database.
This should allow you to accomplish the changeover without interruption to the end user.
Also:
Something I would do is name the new database field something that is completely unrelated to password like "LastSessionID" or something similarly boring. Then instead of removing the password field, just populate with hashes of random data. Then, if your database ever gets compromised, they can spend all the time they want trying to decrypt the "password" field.
This may not actually accomplish anything, but it's fun thinking about someone sitting there trying to figure out worthless information
As with all security decisions, there are tradeoffs. If you hash the password, which is probably your easiest move, you can't offer a password retrieval function that returns the original password, nor can your staff look up a person's password in order to access their account.
You can use symmetric encryption, which has its own security drawbacks. (If your server is compromised, the symmetric encryption key may be compromised also).
You can use public-key encryption, and run password retrieval/customer service on a separate machine which stores the private key in isolation from the web application. This is the most secure, but requires a two-machine architecture, and probably a firewall in between.
MD5 and SHA1 have shown a bit of weakness (two words can result in the same hash) so using SHA256-SHA512 / iterative hashes is recommended to hash the password.
I would write a small program in the language that the application is written in that goes and generates a random salt that is unique for each user and a hash of the password. The reason I tend to use the same language as the verification is that different crypto libraries can do things slightly differently (i.e. padding) so using the same library to generate the hash and verify it eliminates that risk. This application could also then verify the login after the table has been updated if you want as it knows the plain text password still.
Don't use MD5/SHA1
Generate a good random salt (many crypto libraries have a salt generator)
An iterative hash algorithm as orip recommended
Ensure that the passwords are not transmitted in plain text over the wire
I would like to suggest one improvement to the great python example posted by Orip. I would redefine the random_bytes function to be:
def random_bytes(num_bytes):
return os.urandom(num_bytes)
Of course, you would have to import the os module. The os.urandom function provides a random sequence of bytes that can be safely used in cryptographic applications. See the reference help of this function for further details.
To hash the password you can use the HashBytes function. Returns a varbinary, so you'd have to create a new column and then delete the old varchar one.
Like
ALTER TABLE users ADD COLUMN hashedPassword varbinary(max);
ALTER TABLE users ADD COLUMN salt char(10);
--Generate random salts and update the column, after that
UPDATE users SET hashedPassword = HashBytes('SHA1',salt + '|' + password);
Then you modify the code to validate the password, using a query like
SELECT count(*) from users WHERE hashedPassword =
HashBytes('SHA1',salt + '|' + <password>)
where <password> is the value entered by the user.
I'm not a security expert, but i htink the current recommendation is to use bcrypt/blowfish or a SHA-2 variant, not MD5 / SHA1.
Probably you need to think in terms of a full security audit, too

Resources