//1初始化秘钥 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); System.out.println("PublicKey:"+Base64.encodeBase64(rsaPublicKey.getEncoded())); System.out.println("PrivateKey:"+Base64.encodeBase64(rsaPrivateKey.getEncoded())); //2私钥加密,公钥解密——加密 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] result = cipher.doFinal(s.getBytes());//待加密的字符串 System.out.println("加密密文:"+Base64.encodeBase64(result)); //2私钥加密,公钥解密——解密 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded()); KeyFactory keyFactory1 = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory1.generatePublic(x509EncodedKeySpec); Cipher cipher1 = Cipher.getInstance("RSA"); cipher1.init(Cipher.DECRYPT_MODE, publicKey); result = cipher.doFinal(result); System.out.println("解密密文:"+new String(result));
这个是加密的字符串太长了,我也没找到解决方案的,谁有办法请明示
什么鬼
还是报相同的错,只不过
Data must not be longer than 245 bytes
不是245了
keyPairGenerator.initialize(2048); ====>keyPairGenerator.initialize(512); 或
keyPairGenerator.initialize(1024);