小付博客

无话可说...

您现在的位置是:首页>技术分享>RSA加密解密报错Data must not be longer than 117 bytes

RSA加密解密报错Data must not be longer than 117 bytes

发布时间:2019-04-10 编辑:小付 浏览(1023) 评论(0)

    /**
    	 * 公钥加密方法
    	 * 
    	 * @param source 源数据
    	 * @return
    	 * @throws Exception
    	 */
    	private static String encrypt(String source) throws Exception {
    		Key publicKey;
    		ObjectInputStream ois = null;
    		try {
    			/** 将文件中的公钥对象读出 */
    			ois = new ObjectInputStream(
    			    new FileInputStream(
    			        new File("publickey").getAbsolutePath()
    			        +"/pubkey.cer"
    			    )
    			);
    			publicKey = (Key) ois.readObject();
    		} catch (Exception e) {
    			throw e;
    		} finally {
    			ois.close();
    		}
     
    		/** 得到Cipher对象来实现对源数据的RSA加密 */
    		Cipher cipher = Cipher.getInstance("RSA");
    		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    		byte[] b = source.getBytes();
    		/** 执行加密操作 */
    		byte[] enBytes = null;
    		if (b.length>117) {
    			for (int i = 0; i < b.length; i += 64) {
    				// 注意要使用2的倍数,否则会出现加密后的内容再解密时为乱码  
    			    byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(b,i,i+64));
    			    enBytes = ArrayUtils.addAll(enBytes, doFinal);
    			}
    		} else {
    			enBytes = cipher.doFinal(b);
    		}
    		return Base64.encodeToString(enBytes);
    	}


    注意这段:

    for (int i = 0; i < b.length; i += 64) {
    	// 注意要使用2的倍数,否则会出现加密后的内容再解密时为乱码  
    	byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(b, i,i + 64));
    	enBytes = ArrayUtils.addAll(enBytes, doFinal);
    }


关键字词:RSA加密,117 bytes,Data must not be longer than 117 bytes