java.lang.ArrayIndexOutOfBoundsException: too much data for RSA block

后端 未结 3 446
野趣味
野趣味 2021-01-03 13:46

I\'m using RSA encrypt text and decrypt text. The public key and the private key are generated with openssl tool. I encountered an \"java.lang.ArrayIndexOutOfBoundsException

3条回答
  •  [愿得一人]
    2021-01-03 14:05

    Fianlly I modified my codes like that and they work well:

        public static String encryptData(String text, String pub_key) {
            try {
                byte[] data = text.getBytes("utf-8");
                PublicKey publicKey = getPublicKey(Base64.decode(pub_key.getBytes("utf-8"), Base64.DEFAULT));
                Cipher cipher = Cipher.getInstance(RSA);
                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
                return Base64.encodeToString(cipher.doFinal(data),Base64.DEFAULT);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        public static String decryptData(String text, String pri_key) {
            try {
                byte[] data =Base64.decode(text,Base64.DEFAULT);
                PrivateKey privateKey = getPrivateKey(Base64.decode(pri_key.getBytes("utf-8"),Base64.DEFAULT));
    
                Cipher cipher = Cipher.getInstance(RSA);
                cipher.init(Cipher.DECRYPT_MODE, privateKey);
                return new String(cipher.doFinal(data),"utf-8");
            } catch (Exception e) {
                return null;
            }
        }
    

    If something seems wrong still you can remind me. Thanks for James and Henry's answer.

提交回复
热议问题