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

时间:2013-10-04 08:01:36

标签: java jce

我想加密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)

1 个答案:

答案 0 :(得分:2)

在使用加密String时有一个很好的基本示例here。这个例子使用DES,但我相信原理是相同的,所以希望有助于你开始。

您发布的Stack Trace与this post中遇到的问题非常相似。如果您有一个可以为您提供解决方案的外观,那么有一个可接受的答案。

祝你好运!