Вопрос по encryption, passwords, java – PBE: проверьте пароль, прежде чем пытаться расшифровать
Я делаю приложение на Java и хочу разрешить пользователям шифровать файл (или папку - я заархивирую каталог), используя пароль по своему выбору. В настоящее время у меня есть следующие методы:
<code>static Cipher createCipher(int mode, String password) throws Exception { PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(keySpec); MessageDigest md = MessageDigest.getInstance("MD5"); md.update("input".getBytes()); byte[] digest = md.digest(); byte[] salt = new byte[8]; for (int i = 0; i < 8; ++i) salt[i] = digest[i]; PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 20); Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES"); cipher.init(mode, key, paramSpec); return cipher; } static void applyCipher(String inFile, String outFile, Cipher cipher) throws Exception { String decryption = ""; CipherInputStream in = new CipherInputStream(new FileInputStream(inFile), cipher); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile)); int BUFFER_SIZE = 8; byte[] buffer = new byte[BUFFER_SIZE]; int numRead = 0; do { numRead = in.read(buffer); System.out.println(buffer + ", 0, " + numRead); if (numRead > 0){ out.write(buffer, 0, numRead); System.out.println(toHexString(buffer, 0, numRead)); } } while (numRead == 8); in.close(); out.flush(); out.close(); } private static char[] hex_table = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; public static String toHexString(byte[] data, int offset, int length) { StringBuffer s = new StringBuffer(length*2); int end = offset+length; for (int i = offset; i < end; i++) { int high_nibble = (data[i] & 0xf0) >>> 4; int low_nibble = (data[i] & 0x0f); s.append(hex_table[high_nibble]); s.append(hex_table[low_nibble]); } return s.toString(); } </code>
Однако, чтобы сделать программу более удобной для пользователя, я хотел бы иметь возможность проверить, что пользователь ввел правильный пароль перед созданием файла. Я не хочу "оставлять ключ под ковриком у двери". или полностью отменить безопасность и т. д. - я просто хочу предотвратить создание неправильного файла, если пользователь вводит неправильный пароль ...
Любые идеи будут с благодарностью. Если вам нужна дополнительная информация, не стесняйтесь спрашивать.
заранее спасибо
ватель вводит пароль, вы шифруете его и проверяете, присутствует ли в файле тот же зашифрованный пароль. Если нет, вы не загружаете файл.
AEAD режим, как CCM или EAX. Это проверит целостность каждого блока файла во время его дешифрования, в случае неудачи, если ключ неверен или файл был подделан. Поставщик Bouncy Castleподдерживает оба из этих режимов.
а не PBEWithMD5AndDES. У поздних пользователей два разных устаревших примитива. Первый является текущим стандартом.
у вас есть два варианта
Fast but less secure: Put a short known value at the start of your encrypted file or encrypt an entirely different short file under the same password. When you decrypt this file, check for the known value.
Clearly this works quickly. Its slightly less secure because it means an attacker attempting to brute force the password can discard a guessed password faster: instead of having to look at the whole file, they just have to check that value. This is not really a big issue since your key derivation function should be hard enough and they still have to run that
Store the hash of the file encrypted as well and verify the hash on decryption. More secure in that the attacker has to decrypt the whole file and read through it, but by the same token it is slow.
InvalidKeySpecException: Salt not found
, Кто-нибудь знает почему? Я использую последнюю версию Java / JDK.
Andy