EzDevInfo.com

cryptography

cryptography is a package designed to expose cryptographic primitives and recipes to Python developers. Welcome to cryptography — Cryptography 1.1.dev1 documentation

What RSA key length should I use for my SSL certificates?

I'm in the process of creating a CSR, and I wonder which is arguably the best length for my RSA key.

Of course, 384 is probably too weak, and 16384 is probably too slow.

Is there a consensus on the key length one should use, depending on the certificate lifetime?

Edit : Like most people, I want my key to be reasonably strong. I'm not concerned that the NSA could maybe break my key in 2019. I just want to know what's the best practice when one plan to do normal business (for example an e-commerce site)


Source: (StackOverflow)

Are there any PHP implementations of scrypt? [closed]

Where can I find a free scrypt implementation for PHP? Searching Google doesn't provide any useful results because "scrypt" is such an overloaded term.


Source: (StackOverflow)

Advertisements

Blackberry smartcard reader example

I am writing an app for BlackBerry that utilizes a BlackBerry smartcard reader. There is not much documentation on the subject, so I'd really like if someone could give me starting examples.

Basically, there is one RSA private key on the card plus a certificate (for paired public key). I would like to be able to encrypt/decrypt data and also sign it as well. The final goal would be to establish an mutual-authenticated SSL connection using client certificate contained on the smartcard.

Here is the code I managed to come up with so far:

SmartCardReader btReader = null;
SmartCardReader[] readers = SmartCardReaderFactory.getInstalledReaders();
for (int i = 0; i < readers.length; i++) {
    SmartCardReader reader = readers[i];
    if (reader.getType().equalsIgnoreCase("bluetooth")) {
        btReader = reader;
        break;
    }
}

SmartCardReaderSession readerSession = reader.openSession();
CryptoSmartCard card = (CryptoSmartCard) readerSession.getSmartCard();
RSACryptoToken token = (RSACryptoToken) card.getCryptoToken("RSA");

This token looks promising - has some nice methods, but with "cryptic" arguments. What to do next?


Source: (StackOverflow)

How do I enable perfect forward secrecy by default on Apache?

In the wake of recent events, I have been reconsidering my Apache setup. Currently, my apache site config looks something like this:

 <IfModule mod_ssl.c>
    <VirtualHost *:80>
            ServerName mydomain.com
            ServerAlias www.mydomain.com
            Redirect permanent / https://mydomain.com
    </VirtualHost>

    <VirtualHost *:443>
            ServerAdmin webmaster@localhost
            ServerName mydomain.com

            DocumentRoot /var/www-wordpress
            <Directory />
                    Options FollowSymLinks
                    AllowOverride None
            </Directory>
            <Directory /var/www-wordpress>
                    Options Indexes FollowSymLinks MultiViews
                    AllowOverride FileInfo
                    Order allow,deny
                    allow from all
            </Directory>

            ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
            <Directory "/usr/lib/cgi-bin">
                    AllowOverride None
                    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                    Order allow,deny
                    Allow from all
            </Directory>

            ErrorLog ${APACHE_LOG_DIR}/error.log
            LogLevel warn

            CustomLog ${APACHE_LOG_DIR}/ssl_access.log combined
            SSLCertificateFile    /etc/ssl/certs/mydomain.com.crt
            SSLCertificateKeyFile /etc/ssl/private/mydomain.com.key
            SSLCertificateChainFile /etc/ssl/certs/sub.class1.server.ca.pem
            <FilesMatch "\.(cgi|shtml|phtml|php)$">
                    SSLOptions +StdEnvVars
            </FilesMatch>
            <Directory /usr/lib/cgi-bin>
                    SSLOptions +StdEnvVars
            </Directory>

            BrowserMatch "MSIE [2-6]" \
                    nokeepalive ssl-unclean-shutdown \
                    downgrade-1.0 force-response-1.0
            BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
    </VirtualHost>

What do I have to do to support perfect forward secrecy? How can I enable SSL perfect forward secrecy by default? How could I enforce it?


Source: (StackOverflow)

Encrypt Password in Configuration Files?

I have a program that reads server information from a configuration file and would like to encrypt the password in that configuration that can be read by my program and decrypted.

Requirments:

  • Encrypt plaintext password to be stored in the file
  • Decrypt the encrypted password read in from the file from my program

Any reccomendations on how i would go about doing this? I was thinking of writing my own algorithm but i feel it would be terribly insecure.


Source: (StackOverflow)

Login without HTTPS, how to secure?

For a webapplication, when HTTPS is not available as a security measure, is it possible to still make the login somewhat secure? E.g.:

  • Tokenize logins, to make repeat attacks difficult?
  • Somehow encrypt the sent password from a HTML password field?

In particular I'm using CakePHP and an AJAX POST call to trigger authentication (includes provided username and password).

Update on the problem:

  • HTTPS is not available. Period. If you don't like the the situation, consider it a theoretical question.
  • There are no explicit requirements, you have whatever HTTP, PHP and a browser (cookies, JavaScript etc.) offers in real life (no magic RSA binaries, PGP plugins).
  • Question is, what is the best, you can make out of this situation, that is better than sending the passwords plaintext. Knowing the drawbacks of each such solutions is a plus.
  • Any improvement better than plain passwords is welcome. We do not aim for a 100% l33tG0Dhx0r-proff solution. Difficult to crack is better than complicated to hack which is better than a trivial sniffing revealing the password.

Source: (StackOverflow)

Microsoft Crypto API Disable Use of RSAES-OAEP Key Transport Algorithm

I'm using CryptEncryptMessage to generate a PKCS#7 enveloped message. I'm using szOID_NIST_AES256_CBC as the encryption algorithm.

The generated message appears to be valid but is the RSAES-OAEP for the Key Transport Algorithm which has limited support in the wild (Thunderbird, OpenSSL SMIME Module among many others don't support it).

I'll like for CAPI to revert to the older RSAencryption for key transport.

Is there any possible way to do that, I could revert to the low level messaging functions if there is a way rather than to use CryptEncryptMessage but I can't find a way to do that even using the low level functions.

Code:

CRYPT_ENCRYPT_MESSAGE_PARA EncryptMessageParams;
EncryptMessageParams.cbSize = sizeof(CMSG_ENVELOPED_ENCODE_INFO);

EncryptMessageParams.dwMsgEncodingType = PKCS_7_ASN_ENCODING;

EncryptMessageParams.ContentEncryptionAlgorithm.pszObjId = szOID_NIST_AES256_CBC;
EncryptMessageParams.ContentEncryptionAlgorithm.Parameters.cbData = 0;
EncryptMessageParams.ContentEncryptionAlgorithm.Parameters.pbData = 0;

EncryptMessageParams.hCryptProv = NULL;
EncryptMessageParams.pvEncryptionAuxInfo = NULL;
EncryptMessageParams.dwFlags = 0;
EncryptMessageParams.dwInnerContentType = 0;

BYTE pbEncryptedBlob[640000];
DWORD pcbEncryptedBlob = 640000;

BOOL retval =  CryptEncryptMessage(&EncryptMessageParams, cRecipientCert, pRecipCertContextArray, pbMsgText, dwMsgTextSize, pbEncryptedBlob, &pcbEncryptedBlob);

Source: (StackOverflow)

Non-random salt for password hashes

UPDATE: I recently learned from this question that in the entire discussion below, I (and I am sure others did too) was a bit confusing: What I keep calling a rainbow table, is in fact called a hash table. Rainbow tables are more complex creatures, and are actually a variant of Hellman Hash Chains. Though I believe the answer is still the same (since it doesnt come down to cryptanalysis), some of the discussion might be a bit skewed.
The question: "What are rainbow tables and how are they used?"


Typically, I always recommend using a cryptographically-strong random value as salt, to be used with hash functions (e.g. for passwords), such as to protect against Rainbow Table attacks.

But is it actually cryptographically necessary for the salt to be random? Would any unique value (unique per user, e.g. userId) suffice in this regard? It would in fact prevent using a single Rainbow Table to crack all (or most) passwords in the system...
But does lack of entropy really weaken the cryptographic strength of the hash functions?


Note, I am not asking about why to use salt, how to protect it (it doesnt need to be), using a single constant hash (don't), or what kind of hash function to use.
Just whether salt needs entropy or not.


Thanks all for the answers so far, but I'd like to focus on the areas I'm (a little) less familiar with. Mainly implications for cryptanalysis - I'd appreciate most if anyone has some input from the crypto-mathematical PoV.
Also, if there are additional vectors that hadn't been considered, thats great input too (see @Dave Sherohman point on multiple systems).
Beyond that, if you have any theory, idea or best practice - please back this up either with proof, attack scenario, or empirical evidence. Or even valid considerations for acceptable trade-offs... I'm familiar with Best Practice (capital B capital P) on the subject, I'd like to prove what value this actually provides.


EDIT: Some really good answers here, but I think as @Dave says, it comes down to Rainbow Tables for common user names... and possible less common names too. However, what if my usernames are globally unique? Not necessarily unique for my system, but per each user - e.g. email address.
There would be no incentive to build a RT for a single user (as @Dave emphasized, the salt is not kept secret), and this would still prevent clustering. Only issue would be that I might have the same email and password on a different site - but salt wouldnt prevent that anyway.
So, it comes back down to cryptanalysis - IS the entropy necessary, or not? (My current thinking is it's not necessary from a cryptanalysis point of view, but it is from other practical reasons.)


Source: (StackOverflow)

Which cryptographic hash function should I choose?

The .NET framework ships with 6 different hashing algorithms:

  • MD5: 16 bytes (Time to hash 500MB: 1462 ms)
  • SHA1: 20 bytes (1644 ms)
  • SHA256: 32 bytes (5618 ms)
  • SHA384: 48 bytes (3839 ms)
  • SHA512: 64 bytes (3820 ms)
  • RIPEMD: 20 bytes (7066 ms)

Each of these functions performs differently; MD5 being the fastest and RIPEMD being the slowest.

MD5 has the advantage that it fits in the built-in Guid type. Which makes it really easy to use for identification.

MD5 however is vulnerable to collision attacks, SHA1 is also vulnerable but to a lesser degree.

Under what conditions should I use which hashing algorithm?

Particular questions I'm really curious to see answered are:

  • Is MD5 not to be trusted? Under normal situations when you use the MD5 algorithm with no malicious intent and no third party has any malicious intent would you expect ANY collisions (meaning two arbitrary byte[] producing the same hash)

  • How much better is RIPEMD than SHA1? (if its any better) its 5 times slower to compute but the hash size is the same as SHA1.

  • What are the odds of getting non-malicious collisions when hashing file-names (or other short strings)? (Eg. 2 random file-names with same MD5 hash) (with MD5 / SHA1 / SHA2xx) In general what are the odds for non-malicious collisions?

This is the benchmark I used:

    static void TimeAction(string description, int iterations, Action func) {
        var watch = new Stopwatch();
        watch.Start();
        for (int i = 0; i < iterations; i++) {
            func();
        }
        watch.Stop();
        Console.Write(description);
        Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds);
    }

    static byte[] GetRandomBytes(int count) {
        var bytes = new byte[count];
        (new Random()).NextBytes(bytes);
        return bytes;
    }


    static void Main(string[] args) {

        var md5 = new MD5CryptoServiceProvider();
        var sha1 = new SHA1CryptoServiceProvider();
        var sha256 = new SHA256CryptoServiceProvider();
        var sha384 = new SHA384CryptoServiceProvider();
        var sha512 = new SHA512CryptoServiceProvider();
        var ripemd160 = new RIPEMD160Managed();

        var source = GetRandomBytes(1000 * 1024);

        var algorithms = new Dictionary<string,HashAlgorithm>();
        algorithms["md5"] = md5;
        algorithms["sha1"] = sha1;
        algorithms["sha256"] = sha256;
        algorithms["sha384"] = sha384;
        algorithms["sha512"] = sha512;
        algorithms["ripemd160"] = ripemd160;

        foreach (var pair in algorithms) {
            Console.WriteLine("Hash Length for {0} is {1}", 
                pair.Key, 
                pair.Value.ComputeHash(source).Length);
        }

        foreach (var pair in algorithms) {
            TimeAction(pair.Key + " calculation", 500, () =>
            {
                pair.Value.ComputeHash(source);
            });
        }

        Console.ReadKey();
    }

Source: (StackOverflow)

Difference between java.util.Random and java.security.SecureRandom

My team got handed over some server side code (in Java) that generates random tokens and I have a question regarding the same -

The purpose of these tokens is fairly sensitive - used for session id, password reset links etc. So they do need to be cryptographically random to avoid somebody guessing them or brute force them feasibly. The token is a "long" so it is 64 bits long.

The code currently uses the java.util.Random class to generate these tokens. The documentation (http://docs.oracle.com/javase/7/docs/api/java/util/Random.html) for java.util.Random clearly states the following:

Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.

However, the way the code is currently using java.util.Random is this - It instantiates the java.security.SecureRandom class and then uses the SecureRandom.nextLong() method to obtain the seed that is used for instantiating the java.util.Randomclass. Then it uses java.util.Random.nextLong() method to generate the token.

So my question now - Is it still insecure given that the java.util.Random is being seeded using java.security.SecureRandom? Do I need to modify the code so that it uses java.security.SecureRandom exclusively to generate the tokens?

Regards

EDIT: Re @Tom's question - Currently the code seed's the Random once at startup


Source: (StackOverflow)

Is SHA-1 secure for password storage?

Conclusion: SHA-1 is as safe as anything against preimage attacks, however it is easy to compute, which means it is easier to mount a bruteforce or dictionary attack. (The same is true for successors like SHA-256.) Depending on the circumstances, a hash function which was designed to be computationally expensive (such as bcrypt) might be a better choice.


Some people throw around remarks like "SHA-1 is broken" a lot, so I'm trying to understand what exactly that means. Let's assume I have a database of SHA-1 password hashes, and an attacker whith a state of the art SHA-1 breaking algorithm and a botnet with 100,000 machines gets access to it. (Having control over 100k home computers would mean they can do about 10^15 operations per second.) How much time would they need to

  1. find out the password of any one user?
  2. find out the password of a given user?
  3. find out the password of all users?
  4. find a way to log in as one of the users?
  5. find a way to log in as a specific user?

How does that change if the passwords are salted? Does the method of salting (prefix, postfix, both, or something more complicated like xor-ing) matter?

Here is my current understanding, after some googling. Please correct in the answers if I misunderstood something.

  • If there is no salt, a rainbow attack will immediately find all passwords (except extremely long ones).
  • If there is a sufficiently long random salt, the most effective way to find out the passwords is a brute force or dictionary attack. Neither collision nor preimage attacks are any help in finding out the actual password, so cryptographic attacks against SHA-1 are no help here. It doesn't even matter much what algorithm is used - one could even use MD5 or MD4 and the passwords would be just as safe (there is a slight difference because computing a SHA-1 hash is slower).
  • To evaluate how safe "just as safe" is, let's assume that a single sha1 run takes 1000 operations and passwords contain uppercase, lowercase and digits (that is, 60 characters). That means the attacker can test 1015*60*60*24 / 1000 ~= 1017 potential password a day. For a brute force attack, that would mean testing all passwords up to 9 characters in 3 hours, up to 10 characters in a week, up to 11 characters in a year. (It takes 60 times as much for every additional character.) A dictionary attack is much, much faster (even an attacker with a single computer could pull it off in hours), but only finds weak passwords.
  • To log in as a user, the attacker does not need to find out the exact password; it is enough to find a string that results in the same hash. This is called a first preimage attack. As far as I could find, there are no preimage attacks against SHA-1. (A bruteforce attack would take 2160 operations, which means our theoretical attacker would need 1030 years to pull it off. Limits of theoretical possibility are around 260 operations, at which the attack would take a few years.) There are preimage attacks against reduced versions of SHA-1 with negligible effect (for the reduced SHA-1 which uses 44 steps instead of 80, attack time is down from 2160 operations to 2157). There are collision attacks against SHA-1 which are well within theoretical possibility (the best I found brings the time down from 280 to 252), but those are useless against password hashes, even without salting.

In short, storing passwords with SHA-1 seems perfectly safe. Did I miss something?

Update: Marcelo pointed out an article which mentions a second preimage attack in 2106 operations. (Edit: As Thomas explains, this attack is a hypothetical construct which does not apply to real-life scenarios.) I still don't see how this spells danger for the use of SHA-1 as a key derivation function, though. Are there generally good reasons to think that a collision attack or a second preimage attack can be eventually turned into a first preimage attack?


Source: (StackOverflow)

Is it possible to decrypt md5 hashes?

Someone told me that he has seen software systems that would accept MD5 encrypted passwords (through various integrations with other systems), decrypt them, and store them in the systems own database using its own algorithm.

Is that possible? I thought that it wasn't possible (feasible) to decrypt MD5 hashes.

I know there are MD5 dictionaries, but is there an actual decryption algorithm?


Source: (StackOverflow)

Salting Your Password: Best Practices?

I've always been curious... Which is better when salting a password for hashing: prefix, or postfix? Why? Or does it matter, so long as you salt?

To explain: We all (hopefully) know by now that we should salt a password before we hash it for storage in the database [Edit: So you can avoid things like what happened to Jeff Atwood recently]. Typically this is done by concatenating the salt with the password before passing it through the hashing algorithm. But the examples vary... Some examples prepend the salt before the password. Some examples add the salt after the password. I've even seen some that try to put the salt in the middle.

So which is the better method, and why? Is there a method that decreases the chance of a hash collision? My Googling hasn't turned up a decent analysis on the subject.

Edit: Great answers folks! I'm sorry I could only pick one answer. :)


Source: (StackOverflow)

How does password salt help against a rainbow table attack?

I'm having some trouble understanding the purpose of a salt to a password. It's my understanding that the primary use is to hamper a rainbow table attack. However, the methods I've seen to implement this don't seem to really make the problem harder.

I've seen many tutorials suggesting that the salt be used as the following:

$hash =  md5($salt.$password)

The reasoning being that the hash now maps not to the original password, but a combination of the password and the salt. But say $salt=foo and $password=bar and $hash=3858f62230ac3c915f300c664312c63f. Now somebody with a rainbow table could reverse the hash and come up with the input "foobar". They could then try all combinations of passwords (f, fo, foo, ... oobar, obar, bar, ar, ar). It might take a few more milliseconds to get the password, but not much else.

The other use I've seen is on my linux system. In the /etc/shadow the hashed passwords are actually stored with the salt. For example, a salt of "foo" and password of "bar" would hash to this: $1$foo$te5SBM.7C25fFDu6bIRbX1. If a hacker somehow were able to get his hands on this file, I don't see what purpose the salt serves, since the reverse hash of te5SBM.7C25fFDu6bIRbX is known to contain "foo".

Thanks for any light anybody can shed on this.

EDIT: Thanks for the help. To summarize what I understand, the salt makes the hashed password more complex, thus making it much less likely to exist in a precomputed rainbow table. What I misunderstood before was that I was assuming a rainbow table existed for ALL hashes.


Source: (StackOverflow)

Where do you store your salt strings?

I've always used a proper per-entry salt string when hashing passwords for database storage. For my needs, storing the salt in the DB next to the hashed password has always worked fine.

However, some people recommend that the salt be stored separately from the database. Their argument is that if the database is compromised, an attacker can still build a rainbow table taking a particular salt string into account in order to crack one account at a time. If this account has admin privileges, then he may not even need to crack any others.

From a security perspective, is it worth it to store salts in a different place? Consider a web application with the server code and DB on the same machine. If the salts are stored in a flat file on that machine, chances are that if the database is compromised, the salts file will be, too.

Are there any recommended solutions to this?


Source: (StackOverflow)