Can I开发者_如何学C use every possible String to create a new SecretKeySpec
? Or will it weaken the entire encryption?
byte[] raw = password.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
It's going to be relatively weak to use the password bytes directly. At the very least you'll want to run them through a strong hash. And throw in a salt, some array of bytes that you can reproduce for the scenario (either static for your app or better something like a fixed user id).
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(password.getBytes());
digest.update(salt);
byte[] raw = digest.digest();
If you really want to make it harder to brute force the password, you could make the hashing more complicated. This for example will only add a few tens of milliseconds for legitimate use cases, however it'll significantly slow down a brute force attack:
for (int i = 0; i < 34000; i++) {
digest.reset();
digest.update(raw);
raw = digest.digest();
}
Ideally you make sure the password is strong as well (length, complexity, mix of upper/lower/number characters). If it's a simple word or short enough then the attack is still going to be easy. Don't trust the obscurity of this hashing either, it doesn't make it any safer. It's use of strong passwords and strong hashing that matter.
To get the full benefit of 128-bit AES the password would need to be around 20 characters long, however 8 to 12 will probably suffice for the majority of concerns. If you're working for my bank please use 20 or more though.
精彩评论