当前位置: 首页 > 知识库问答 >
问题:

如何使用RSA和AES算法加密和解密文件[关闭]

卞成荫
2023-03-14

我想加密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个答案

蒋培
2023-03-14

这里有一个关于用DES加密字符串的很好的基本例子。这个例子使用DES,但是我相信原理是一样的,所以希望能帮助你开始。

您发布的堆栈跟踪与本文中面临的问题非常相似。有一个公认的答案,如果你有一个看,这可能会为你提供一个修复也。

祝你好运

 类似资料:
  • 本文向大家介绍原生js的RSA和AES加密解密算法,包括了原生js的RSA和AES加密解密算法的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了js中RSA和AES加密解密详细代码,供大家参考,具体内容如下 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。

  • 我正在为我的应用程序制作加密/解密模块。我按照这个教程 它没有给出任何错误,也没有显示输出。 日志文件 MainActivity.Java AESHelper.Java } AESHelper.java:52 还有AESHelper.java:25

  • 我的进程: 1。生成对称密钥 2。使用对称密钥 3加密数据。使用RSA 4加密对称密钥。发送加密密钥和数据 5。使用RSA 6解密加密的对称密钥。使用对称密钥 7解密数据。已完成

  • 我正在尝试用AES加密一个大文件,然后解密,与原件进行比较。 这堂课总结了工作。它适用于.txt文件,但不适用于.mp3、.pdf等文件。 我们将非常感谢你的帮助。

  • 问题内容: 我想生成rsa密钥对(公共和私有),然后将它们用于AES加密和解密。例如,用于加密的公共密钥和用于解密的私有密钥。我为此编写了一个简单的代码,但是问题是当我运行时这段代码我得到这个错误: 我该如何解决这个问题?我的加密代码如下: 问题答案: 如评论中所建议,我搜索了“混合密码术”。这个例子解决了我的问题。

  • 我使用的是Web加密,更具体地说,这些示例是:https://github.com/diafygi/webcrypto-examples/#rsa-oaep 更新