Generate random Salt using securerandom - random

I want to generate a random salt...
I am doing this but get the same salt every time even if I restart my program .. i checked using println
SecureRandom random = SecureRandom.getInstance("NativePRNGBlocking");
byte[] salt = new byte[32];
random.nextBytes(salt);
System.out.println(salt);
return salt;
How to generate a random salt? I want a separate salt for each user.

The bytes in the salt array will in fact be different, at least unless the NativePRNGBlocking implementation is broken. I think the problem is in your check. The toString method for byte arrays does not print the values in the array, so printing the salt array in that way is useless. Try to print the individual values:
for(byte b: salt) {
System.out.print(b + " ");
}
Or you could just inspect them in a debugger.

SecureRandom class supports the “SHA1PRNG” pseudo random number generator algorithm.
Try the below code it works fine for me and getting always unique outptut.
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
//Create array for salt
byte[] salt = new byte[32];
//Get a random salt
sr.nextBytes(salt);
//return salt
System.out.println( salt.toString());
Hope it will resolve your issue.

Related

Why is golang package bcrypt able to retrieve the salt after hashing the password?

I am having trouble understanding the following code from the golang crypto bcrypt repo
func newFromHash(hashedSecret []byte) (*hashed, error) {
if len(hashedSecret) < minHashSize {
return nil, ErrHashTooShort
}
p := new(hashed)
n, err := p.decodeVersion(hashedSecret)
if err != nil {
return nil, err
}
hashedSecret = hashedSecret[n:]
n, err = p.decodeCost(hashedSecret)
if err != nil {
return nil, err
}
hashedSecret = hashedSecret[n:]
// The "+2" is here because we'll have to append at most 2 '=' to the salt
// when base64 decoding it in expensiveBlowfishSetup().
p.salt = make([]byte, encodedSaltSize, encodedSaltSize+2)
copy(p.salt, hashedSecret[:encodedSaltSize])
hashedSecret = hashedSecret[encodedSaltSize:]
p.hash = make([]byte, len(hashedSecret))
copy(p.hash, hashedSecret)
return p, nil
}
From my understanding salting is used to prevent adversaries that have hack into the database and obtain a list of hashed passwords, to obtain the original password from the hash, hackers can go through all valid password combinations and hash each one of them, if one of the generated hash match with the hash in the hack DB the hacker can get the password back. Adding a salt before hash force the adversary to regenerate the rainbow table.
The key is to hash the password along with the salt
hash(password + salt)
forcing the hacker to regenerate a rainbow table specifically for the salt
But it seems like bcrypt is able to get the salt back, so technically if an adversary knows a system is using bcrypt he can delete the salt and get the hash password that is not salted.
In another word once the hacker get hashedSecret = hashedSecret[encodedSaltSize:] he can use rainbow attack to get the password back making the salt useless.
Am I getting something wrong?
he can delete the salt and get the hash password that is not salted.
Everything except this part is right.
Imagine, you have a password pass and two salts: s1, s2.
hash(s1 + pass) = 123
hash(s2 + pass) = 456
So you would have two stored records in your DB:
s1$123
s2$456
Deleting the salt part won't get the adversary anywhere as he would still have two different hash digests 123 and 456 to crack.
On the other hand, it would render yourself unable to reconstruct your hash once you get cleartext from your user.
Imagine them sending you pass. What you want to do is to get the salt substring from their hash stored in your DB, e.g. s2$456, then concatenate it with the cleartext and then compare hash(s2 + pass) with 456 above. Without having your salt stored in the database you can't do this, that's why it is necessary.
You can get back the salt but that doesn't mean you get the unsalted password hash. "In another word once the hacker get hashedSecret = hashedSecret[encodedSaltSize:] he can use rainbow attack to get the password back making the salt useless." is misleading. The attacker can get the salt and the hashed password but this doesn't allow a "rainbow attack".
The attack in "rainbow attack" is: Generate a huge rainbow-table once, upfront. The list is a pair of (cleartextpassword,passwordhash) entries. Generating this table is very timeconsuming (and might become large if you include lots of passwords and huge if you include all passwords!). The attack in a "rainbow attack" is: You have to generate this rainbow table only once and can use it to look up cleartext passwords for millions of password-hashes very fast.
As each password in the bcrypt code above gets its own salt you cannot use one rainbow table: You would have to create one rainbow table for each salt. Rendering the "rainbow attack" useless.

Does a particular saltRound generate a unique salt?

1) In the context of bcrypt, does a particular saltRound generate a unique salt?
2) why is it that we don't need to supply the salt when we compare the 'plaintextpassword' with the 'hash'ed password as is the case in the following example:
Example from [https://www.npmjs.com/package/bcrypt][1]
bcrypt.compare(myPlaintextPassword, hash, function(err, res) {
// res == true
});
Usually BCrypt implementations generate a unique salt on their own and include it plaintext in the resulting hash-text. The compare function can extract it from there and use the same salt to calculate a comparable hash.
So no, the salt has nothing to do with rounds, and the compare function extracts it from the stored hash. See this answer, explaining the hash format.

Why don't I need a 32 bit key, or initialization vector for NodeJS crypto?

I was working interchangeably with Node's crypto library and Ruby's OpenSSL library.
The challenge I was coming across was that I could encrypt usingaes256 in both libraries.
However, in node using the crypto.createDecipher('aes256', key) I could have a key that was less than 32 bits long, but ruby would throw an error saying the key is not long enough when using:
cipher = OpenSSL::Cipher.new 'aes256'
cipher.encrypt
key = 'geeses'
I also don't have to set an initialization vector for node, but ruby seems to set one under the covers. I'm pretty new to this crypto stuff, what's going on here?
While #mscdex answers is perfectly, I want to add how to get a cipher with a specific key when your algorithm does not require Initialization Vector using the crypto.createCipheriv or crypto.createDecipheriv
Taking the case of AES-256-ECB where chaining is not done and hence IV is not used.
You can pass empty Buffer as IV.
var data = "plaintext";
const key = crypto.randomBytes(32);
var iv = new Buffer('');
var cipher = crypto.createCipheriv('AES-256-ECB',key,iv);
var encrypted = cipher.update(data,'utf8','base64');
encrypted += cipheriv.final('base64');
console.log('encrypted AES-256-ECB',encrypted);
And decrypt fairly simply using the same pattern:
var decipheriv = crypto.createDecipheriv('AES-256-ECB',key,iv);
var decryptediv = decipheriv.update(encrypted,'base64','utf8');
decryptediv += decipheriv.final('utf8');
console.log('decrypted base64 aes-256 ',decryptediv);
When you use crypto.createDecipher(), the value you pass as the second argument is a password from which a key and IV will be derived (using one iteration of MD5 hashing). This is accomplished by using EVP_BytesToKey() to create those two values. OpenSSL knows the correct lengths both values need to be because the cipher is also passed to EVP_BytesToKey().
So most likely the Ruby function is more analogous to node's crypto.createDecipheriv() which accepts both a key and an IV (which need to be the right lengths for the cipher).

Ruby OpenSSL AES-128-CTR

I can't figure out what I am doing wrong here trying to decrypt a string of hex values with a given key using ruby's OpenSSL cipher AES-128-CTR.
I am using the gem hex_string to convert my hex to bytes
ctrkey = "36f18357be4dbd77f050515c73fcf9f2"
ciphertext3 = "69dda8455c7dd4254bf353b773304eec0ec7702330098ce7f7520d1cbbb20fc3\
88d1b0adb5054dbd7370849dbf0b88d393f252e764f1f5f7ad97ef79d59ce29f5f51eeca32eabedd9afa9329"
cipher2 = OpenSSL::Cipher.new('AES-128-CTR')
cipher2.decrypt
ctrkey = ctrkey.to_byte_string
cipher2.key = ctrkey
iv = cipher2.random_iv
cipher2.iv = iv
ciphertext3 = ciphertext3.to_byte_string
plain = cipher2.update(ciphertext3) + cipher2.final
puts "plaintext of Q3: #{plain}"
I know I am missing something small because I have similar code implementing AES-128-CBC. Do I need to have a counter that increments the IV for each block of 128 bytes in the ciphertext?
No, you're not missing something small, you are missing something huge.
Instead of using the same IV as used for encryption, you are generating a new one. For CTR, if the IV is random then each counter value is different, resulting in random looking output.
Often the IV (or nonce in the case of CTR) is prefixed to the ciphertext. For CTR that may be fewer bytes than 16 - although that is still the most probable size to try.

How to find insertions/deletions by comparing hashes quickly?

I want to create a hash of a file such that if the file is changed I can determine what parts of the file changed. The problem is that if a byte is removed or added, all subsequent hashes change too, therefore I need to iterate per byte through all hashes. This however can be expensive so I am looking for a hash which doesnt require that I recompute the entire hash start to finish but rather lets me undo one byte and then add another byte.
Pseudocode:
string getFileDiffHash(file){
string result = "";
for each (512 bytes in file){
result += hash(bytes);
}
}
string getFileDiff(file, diffHash){
string result = "";
for each (hash size bytes in diffHash){ //yes this would be in a hash table ideally, but hey, this is pseudocode
string current_hash = "";
for (i = 0; i < file_size(file); i++){
if (current_hash.size > hash_size){
current_hash = undo_hash(current_hash, file[i-hash_size]);
}
current_hash = add_hash(current_hash, file[i]);
if (current_hash.size == hash_size && bytes == current_hash){
result += "+"+diffHash+":"+i;
}
}
}
return result;
}
Any idea on what sort of hash would be suited to 'undo_hash' and 'add_hash'?
If you can have a hash of length log2(N) bytes, you can use a Hamming code. If it must be shorter, then a Low-density parity-check code would do the job.
#Interjay's comment was correct, I need a rolling hash. Furthermore, the algorithm I describe here is similar to what rsync does (and Dropbox by extension).

Resources