Reading encrypted data from a file

帅比萌擦擦* 提交于 2019-11-30 17:03:54
nattyddubbs

Here's how you write your key to a file:

        //Write your key to an output file.
        byte[] keyAsByte = key.getEncoded();
        FileOutputStream keyfos = new FileOutputStream("key.txt");
        keyfos.write(keyAsByte);
        keyfos.close();

I wouldn't recommend putting the key with the encrypted text in the same file.

Here's how you read the encrypted text and the key back and decrypt:

    //Read your key
    FileInputStream keyFis = new FileInputStream("key.txt");
    byte[] encKey = new byte[keyFis.available()];
    keyFis.read(encKey);
    keyFis.close();
    Key keyFromFile = new SecretKeySpec(encKey, "DES");
    //Read your text
    FileInputStream encryptedTextFis = new FileInputStream("test.txt");
    byte[] encText = new byte[encryptedTextFis.available()];
    encryptedTextFis.read(encText);
    encryptedTextFis.close();
    //Decrypt
    Cipher decrypter = Cipher.getInstance("DES/ECB/PKCS5Padding");
    decrypter.init(Cipher.DECRYPT_MODE, keyFromFile);
    byte[] decryptedText = decrypter.doFinal(encText);
    //Print result
    System.out.println("Decrypted Text: " + new String(decryptedText));

Note: I didn't use the same path as you for writing the information.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!