Java 如何使用 RSA 和 AES 算法加密和解密文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19176207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:45:28  来源:igfitidea点击:

How to Encrypt and Decrypt file Using RSA And AES Algorithm

javajce

提问by sufala

I want to encrypt test.txt file I am using this java class for encryption and decryption.In My directory I have three files private.txt for save private key and public.txt for public key and test.txt is for encryption.

我想加密 test.txt 文件我使用这个 java 类进行加密和解密。在我的目录中,我有三个文件 private.txt 用于保存私钥,public.txt 用于公钥,test.txt 用于加密。

    package EncryptionDecryption;
    import java.io.BufferedInputStream;


    public class EncryptionUtil {

      /**
       * String to hold name of the encryption algorithm.
       */
      public static final String ALGORITHM = "RSA";

      /**
       * String to hold the name of the private key file.
       */
      public static final String PRIVATE_KEY_FILE = "private.txt";

      /**
       * String to hold name of the public key file.
       */
      public static final String PUBLIC_KEY_FILE = "public.txt";


      public static void generateKey() {
        try {
          final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
          keyGen.initialize(1024);
          final KeyPair key = keyGen.generateKeyPair();

          File privateKeyFile = new File(PRIVATE_KEY_FILE);
          File publicKeyFile = new File(PUBLIC_KEY_FILE);

          // Create files to store public and private key
          if (privateKeyFile.getParentFile() != null) {
            privateKeyFile.getParentFile().mkdirs();
          }
          privateKeyFile.createNewFile();

          if (publicKeyFile.getParentFile() != null) {
            publicKeyFile.getParentFile().mkdirs();
          }
          publicKeyFile.createNewFile();

          // Saving the Public key in a file
          ObjectOutputStream publicKeyOS = new ObjectOutputStream(
              new FileOutputStream(publicKeyFile));
          publicKeyOS.writeObject(key.getPublic());
          System.out.println("public"+key.getPublic().getEncoded());
          publicKeyOS.close();

          // Saving the Private key in a file
          ObjectOutputStream privateKeyOS = new ObjectOutputStream(
              new FileOutputStream(privateKeyFile));
          privateKeyOS.writeObject(key.getPrivate());
          System.out.println("private"+key.getPrivate().getEncoded());
          //System.out.println(key.getPrivate());
          privateKeyOS.close();
        } catch (Exception e) {
          e.printStackTrace();
        }

      }

      public static boolean areKeysPresent() {

        File privateKey = new File(PRIVATE_KEY_FILE);
        File publicKey = new File(PUBLIC_KEY_FILE);

        if (privateKey.exists() && publicKey.exists()) {
          return true;
        }
        return false;
      }


      public static byte[] encrypt(byte[]bs, PublicKey key) {
        byte[] cipherText = null;
        try {
          // get an RSA cipher object and print the provider
          final Cipher cipher = Cipher.getInstance(ALGORITHM);
          // encrypt the plain text using the public key
          cipher.init(Cipher.ENCRYPT_MODE, key);
          cipherText = cipher.doFinal(bs);
        } catch (Exception e) {
          e.printStackTrace();
        }
        return cipherText;
      }


      public static String decrypt(byte[] text, PrivateKey key) {
        byte[] dectyptedText = null;
        try {
          // get an RSA cipher object and print the provider
          final Cipher cipher = Cipher.getInstance(ALGORITHM);

          // decrypt the text using the private key
          cipher.init(Cipher.DECRYPT_MODE, key);
          dectyptedText = cipher.doFinal(text);

        } catch (Exception ex) {
          ex.printStackTrace();
        }

        return new String(dectyptedText);
      }

      public static void main(String[] args)throws IOException {
          System.out.println("Hai");

        try {

          // Check if the pair of keys are present else generate those.


            generateKey();
            File f=new File("test.txt");
            byte[] contents = new byte[(int)f.length()];
            BufferedInputStream bis = null;
            try
            {
                bis = new BufferedInputStream(new FileInputStream(f));
                DataInputStream dis = new DataInputStream(bis);
                dis.readFully(contents);
            }
            finally
            {
                if(bis != null)
                {
                    bis.close();
                }
            }           


         // final String originalText = "Text to be encrypted";


          // Encrypt the string using the public key
          ObjectInputStream  inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
          final PublicKey publicKey = (PublicKey) inputStream.readObject();
          final byte[] cipherText = encrypt(contents, publicKey);
          inputStream.close();
          // Decrypt the cipher text using the private key.
          ObjectInputStream inputStream1 = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
          final PrivateKey privateKey = (PrivateKey) inputStream1.readObject();
          final String plainText = decrypt(cipherText, privateKey);

          // Printing the Original, Encrypted and Decrypted Text

          System.out.println("Original Text: " + contents.toString());
          System.out.println("Encrypted Text: " +cipherText);
          System.out.println("Decrypted Text: " + plainText);
          inputStream.close();
          inputStream1.close();

        } catch (Exception e) {
          e.printStackTrace();
        }
        finally
        {

        }

        }
      }




I got this error when debugging

I

    public[B@f73c1
    private[B@15b9e68
    javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes
        at com.sun.crypto.provider.RSACipher.a(DashoA13*..)
        at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)
        at javax.crypto.Cipher.doFinal(DashoA13*..)
        at EncryptionDecryption.EncryptionUtil.encrypt(EncryptionUtil.java:122)
        at EncryptionDecryption.EncryptionUtil.main(EncryptionUtil.java:193)
    java.lang.IllegalArgumentException: Null input buffer
        at javax.crypto.Cipher.doFinal(DashoA13*..)
        at EncryptionDecryption.EncryptionUtil.decrypt(EncryptionUtil.java:147)
        at EncryptionDecryption.EncryptionUtil.main(EncryptionUtil.java:198)
    java.lang.NullPointerException
        at java.lang.String.<init>(String.java:593)
        at EncryptionDecryption.EncryptionUtil.decrypt(EncryptionUtil.java:153)
        at EncryptionDecryption.EncryptionUtil.main(EncryptionUtil.java:198)

采纳答案by Levenal

There is a good basic example hereon encrypting a String with. This example uses DES but I belive the principle is the same and so will hopefully help get you started.

这里有一个很好的基本示例用于加密字符串。此示例使用 DES,但我相信原理是相同的,因此希望能帮助您入门。

The Stack Trace you have posted is very similar to the issue faced in this post. There is an accepted answer there if you have a look which may provide you with a fix also.

你已经张贴堆栈跟踪非常相似,面临的问题,这个帖子。如果您看一下,那里有一个可接受的答案,它也可以为您提供修复。

Good luck!

祝你好运!