RSA非对称加密

    xiaoxiao2021-03-25  172

    RSA非对称加密

    public class AsymmetricEncryptionDemo01 {

    public static void main(String[] args) throws Exception { String content = "也不会反对呀发神经的沙发上的快感"; //非对称加密用公钥加密 KeyPairGenerator pairGenerator = KeyPairGenerator.getInstance("RSA"); //得到秘钥对 KeyPair keyPair = pairGenerator.generateKeyPair(); //获取公钥 PublicKey publicKey = keyPair.getPublic(); String encryptData = encrypt(content, publicKey);//得到加密后的内容 System.out.println(encryptData); //解密 String decryptData = decrypt(encryptData, privateKey); System.out.println(decryptData); } /** * 解密 * @param encryptData * @param privateKey * @return */ public static String decrypt(String encryptData,PrivateKey privateKey)throws Exception{ byte[] bytes = Base64.getDecoder().decode(encryptData); //获取cipher单例对象 Cipher cipher = Cipher.getInstance("RSA"); //初始化解密,传入私钥 cipher.init(Cipher.DECRYPT_MODE, privateKey); //正式解密 Data must not be longer than 128 bytes //byte[] decryptBytes = cipher.doFinal(bytes);//生成加密后的字节数组 byte[] decryptBytes = doFinalWithBlock(cipher, bytes, 128); return new String(decryptBytes); } /** * 加密方法 * @param content * @param publicKey * @return */ public static String encrypt(String content,PublicKey publicKey)throws Exception{ //获取cipher单例对象 Cipher cipher = Cipher.getInstance("RSA"); //初始化加密,传入公钥 cipher.init(Cipher.ENCRYPT_MODE, publicKey); //正式加密,一次性加密数据的长度不能超过117个字节! //byte[] encryptBytes = cipher.doFinal(content.getBytes());//生成加密后的字节数组 byte[] bytes = content.getBytes(); byte[] encryptBytes = doFinalWithBlock(cipher, bytes,117); return Base64.getEncoder().encodeToString(encryptBytes); } /** * 分块来对大数据进行加密解密 * @param cipher * @param bytes * @param max * @return * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws IOException */ private static byte[] doFinalWithBlock(Cipher cipher, byte[] bytes,int max) throws IllegalBlockSizeException, BadPaddingException, IOException { int length = bytes.length;//要加密的字节数组的长度 int inputOffset = 0;//开始加密的位置 ByteArrayOutputStream baos = new ByteArrayOutputStream(); while(inputOffset < length){//如果要开始加密的位置比bytes的长度大了就说明全部加密完了 if (length - inputOffset >= max) { byte[] encryptBytes = cipher.doFinal(bytes, inputOffset, max); //每次加密得到字节数组就写入字节数组输出流中 baos.write(encryptBytes); inputOffset += max; }else { //说明剩下的字节长度小于117,全部加密完剩下的所有字节 byte[] encryptBytes = cipher.doFinal(bytes, inputOffset, length - inputOffset); baos.write(encryptBytes); inputOffset = length; } } byte[] encryptBytes = baos.toByteArray(); return encryptBytes; }

    }

    转载请注明原文地址: https://ju.6miu.com/read-2331.html

    最新回复(0)