解密时报如下异常: javax.crypto.IllegalBlockSizeException: Data must not be longer than 245 bytes

来源:3-1 RSA算法实现及应用

慕粉4196815

2016-10-18 10:52

//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));


写回答 关注

4回答

  • qq_夢约绿都_0
    2019-07-08 17:53:31

    这个是加密的字符串太长了,我也没找到解决方案的,谁有办法请明示

  • lanzhoujiaoya
    2018-04-08 17:57:15

    什么鬼

  • 慕粉4196815
    2016-10-19 13:52:06

    还是报相同的错,只不过

    Data must not be longer than 245 bytes

    不是245了



  • 银鸽
    2016-10-18 14:17:44

    keyPairGenerator.initialize(2048);  ====>keyPairGenerator.initialize(512); 或

    keyPairGenerator.initialize(1024);

JAVA实现非对称加密

非对称加密算法在JAVA中的实现,了解非对称加密算法应用场景

27470 学习 · 36 问题

查看课程

相似问题