How to Encrypt or Decrypt a File in Java?

后端 未结 2 1053
不思量自难忘°
不思量自难忘° 2020-12-13 23:07

I want to encrypt and decrypt a file in java, i had read this url http://www-users.york.ac.uk/~mal503/lore/pkencryption.htm and i got two files namely public Security certif

相关标签:
2条回答
  • 2020-12-13 23:18

    You simply have muddled your files. This code works using the DER files generated from openssl as described in the article you linked:

        FileEncryption secure = new FileEncryption();
    
        // Encrypt code
        {
            File encryptFile = new File("encrypt.data");
            File publicKeyData = new File("public.der");
            File originalFile = new File("sys_data.db");
            File secureFile = new File("secure.data");
    
            // create AES key
            secure.makeKey();
    
            // save AES key using public key
            secure.saveKey(encryptFile, publicKeyData);
    
            // save original file securely 
            secure.encrypt(originalFile, secureFile);
        }
    
        // Decrypt code
        {
            File encryptFile = new File("encrypt.data");
            File privateKeyFile = new File("private.der");
            File secureFile = new File("secure.data");
            File unencryptedFile = new File("unencryptedFile");
    
            // load AES key
            secure.loadKey(encryptFile, privateKeyFile);
    
            // decrypt file
            secure.decrypt(secureFile, unencryptedFile);
        }
    
    0 讨论(0)
  • 2020-12-13 23:20

    Here is the Simplest Piece of Code for encrypting a document with any Key(Here Random Key)

    randomKey = randomKey.substring(0, 16);
            keyBytes = randomKey.getBytes();
            key = new SecretKeySpec(keyBytes, "AES");
            paramSpec = new IvParameterSpec(iv);
            ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(encryptedFile);
            out = new CipherOutputStream(out, ecipher);
            int numRead = 0;
            while ((numRead = in.read(buf)) >= 0) {
                out.write(buf, 0, numRead);
            }
            in.close();
            out.flush();
            out.close();
    
    0 讨论(0)
提交回复
热议问题