Reading encrypted data from a file

后端 未结 1 389
遥遥无期
遥遥无期 2021-01-03 17:06

I was going through an IBM tutorial on encrypting using Private key. And I wrote the code as below

import java.security.*;
import javax.crypto.*;

// encrypt         


        
1条回答
  •  再見小時候
    2021-01-03 18:08

    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.

    0 讨论(0)
提交回复
热议问题