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

Java 如何使用RSA和AES算法对文件进行加密和解密,java,jce,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 e

我想加密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)
包加密解密;
导入java.io.BufferedInputStream;
公共类EncryptionUtil{
/**
*用于保存加密算法名称的字符串。
*/
公共静态最终字符串算法=“RSA”;
/**
*字符串以保存私钥文件的名称。
*/
公共静态最终字符串PRIVATE\u KEY\u FILE=“PRIVATE.txt”;
/**
*用于保存公钥文件名的字符串。
*/
公共静态最终字符串public\u KEY\u FILE=“public.txt”;
公共静态void generateKey(){
试一试{
final KeyPairGenerator keyGen=KeyPairGenerator.getInstance(算法);
密钥初始化(1024);
final KeyPair key=keyGen.generateKeyPair();
File privateKeyFile=新文件(私钥文件);
文件publicKeyFile=新文件(公钥文件);
//创建文件以存储公钥和私钥
if(privateKeyFile.getParentFile()!=null){
privateKeyFile.getParentFile().mkdirs();
}
privateKeyFile.createNewFile();
如果(publicKeyFile.getParentFile()!=null){
publicKeyFile.getParentFile().mkdirs();
}
publicKeyFile.createNewFile();
//将公钥保存在文件中
ObjectOutputStream publicKeyOS=新的ObjectOutputStream(
新文件输出流(publicKeyFile));
publicKeyOS.writeObject(key.getPublic());
System.out.println(“public”+key.getPublic().getEncoded());
publicKeyOS.close();
//将私钥保存到文件中
ObjectOutputStream privateKeyOS=新的ObjectOutputStream(
新文件输出流(privateKeyFile));
writeObject(key.getPrivate());
System.out.println(“private”+key.getPrivate().getEncoded());
//System.out.println(key.getPrivate());
privateKeyOS.close();
}捕获(例外e){
e、 printStackTrace();
}
}
公共静态布尔值areKeysPresent(){
文件私钥=新文件(私钥文件);
文件公钥=新文件(公钥文件);
if(privateKey.exists()&&publicKey.exists()){
返回true;
}
返回false;
}
公共静态字节[]加密(字节[]bs,公钥){
字节[]密文=空;
试一试{
//获取RSA密码对象并打印提供程序
final Cipher=Cipher.getInstance(算法);
//使用公钥加密纯文本
cipher.init(cipher.ENCRYPT_模式,密钥);
密文=cipher.doFinal(bs);
}捕获(例外e){
e、 printStackTrace();
}
返回密文;
}
公共静态字符串解密(字节[]文本,私钥){
字节[]dectyptedText=null;
试一试{
//获取RSA密码对象并打印提供程序
final Cipher=Cipher.getInstance(算法);
//使用私钥解密文本
cipher.init(cipher.DECRYPT_模式,密钥);
dectyptedText=cipher.doFinal(文本);
}捕获(例外情况除外){
例如printStackTrace();
}
返回新字符串(dectyptedText);
}
公共静态void main(字符串[]args)引发IOException{
系统输出打印号(“Hai”);
试一试{
//检查这对密钥是否存在,否则生成这些密钥。
generateKey();
文件f=新文件(“test.txt”);
字节[]内容=新字节[(int)f.length()];
BufferedInputStream bis=null;
尝试
{
bis=新的BufferedInputStream(新的FileInputStream(f));
DataInputStream dis=新的DataInputStream(bis);
易于阅读(内容);
}
最后
{
如果(bis!=null)
{
二、关闭();
}
}           
//最终字符串originalText=“要加密的文本”;
//使用公钥加密字符串
ObjectInputStream inputStream=新ObjectInputStream(新文件inputStream(公共密钥文件));
final PublicKey PublicKey=(PublicKey)inputStream.readObject();
最终字节[]密文=加密(内容,公钥);
inputStream.close();
//使用私钥解密密文。
ObjectInputStream inputStream1=新ObjectInputStream(新文件InputStream(私有密钥文件));
final PrivateKey PrivateKey=(PrivateKey)inputStream1.readObject();
最终字符串明文=解密(密文、私钥);
//打印原始、加密和解密文本
System.out.println(“原始文本:+contents.toString());
System.out.println(“加密文本:“+密文”);
System.out.println(“解密文本:+纯文本”);
inputStream.close();
inputStream1.close();
}捕获(例外e){
e、 printStackTrace();
}
最后
{
}
}
}
我在调试时遇到了这个错误
我
公开的[B@f73c1
私人的[B@15b9e68
javax.crypto.IllegalBlockSizeException:数据长度不得超过117字节
在com.sun.crypto.provider.rsacyper.a(DashoA13*)上
在com.sun.crypto.provider.rsacyper.engineDoFinal(DashoA13*)上
位于javax.crypto.Cipher.doFinal(DashoA13*)
在EncryptionDecryption.EncryptionUtil.encrypt处(EncryptionUtil.java:122)
位于EncryptionDecryption.EncryptionUtil.main(EncryptionUtil.java:193)
java.lang.I