RSA Data must start with zero问题解决方法

RSA工具使用公钥加密之后生成byte[] ,直接解密是没有问题的,但将byte[]通过Base64.encode(byte[])之后得到的字符串重新getBytes()去解密是会出现RSA Data must start with zero的问题的。

解决方法:

/**
	 * 将加密后的字节数组转换为对象
	 * 
	 * @MethodName: bytesToString 
	 * @Description: 
	 * @param encrytpByte
	 * @return
	 * @throws
	 */
	public static String bytesToString(byte[] encrytpByte) {
	     String result = "";
	     for (Byte bytes : encrytpByte) {
	         result += bytes.toString() + " ";
	     }
	     return result;
	 }
	
	/**
	 * 公钥加密
	 * 
	 * @MethodName: encrypt 
	 * @Description: 
	 * @param publicKey
	 * @param obj
	 * @return
	 * @throws
	 */
	public static byte[] encrypt(RSAPublicKey publicKey, byte[] obj) {
	     if (publicKey != null) {
	         try {
	             Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
	             cipher.init(Cipher.ENCRYPT_MODE, publicKey);
	             return cipher.doFinal(obj);
	         } catch (Exception e) {
	             e.printStackTrace();
	         }
	     }
	     return null;
	 }
	
	/**
	 * 私钥解密
	 * 
	 * @MethodName: decrypt 
	 * @Description: 
	 * @param privateKey
	 * @param obj
	 * @return
	 * @throws
	 */
	public static byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) {
	     if (privateKey != null) {
	         try {
	             Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
	             cipher.init(Cipher.DECRYPT_MODE, privateKey);
	             return cipher.doFinal(obj);
	         } catch (Exception e) {
	             e.printStackTrace();
	         }
	     }
	     return null;
	 }
测试方法:

	@Test
	public void testRSA() throws Exception{
		
		String publicKey=EhcacheUtil.get(StaticProperty.WMS_OPEN_API_RSA_PUBLIC_KEY).toString();
		
		String privateKey=EhcacheUtil.get(StaticProperty.WMS_OPEN_API_RSA_PRIVATE_KEY).toString();
		
		String platformCode="1234",tenantCode="10000";
	    
		byte [] bytes=SAASTokenManager.generateBytesToken(publicKey, platformCode, tenantCode);
		
		System.out.println("RSA bites 加密:"+new String(bytes)); 
		
		System.out.println("RSA bites 解密:"+new String(RSAUtils.decryptByPrivateKey(bytes, privateKey)));
		
		// 将bytes转换为String
		String bytesStr = RSAUtils.bytesToString(bytes);
		
		String[] strArr = bytesStr.split(" ");
        
        int len = strArr.length;
        
        // 转回bytes
        byte[] clone = new byte[len];
         
        for (int i = 0; i < len; i++) {
             clone[i] = Byte.parseByte(strArr[i]);
        }
		
		System.out.println("RSA bites 解密:"+new String(RSAUtils.decryptByPrivateKey(clone, privateKey)));
		
	}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值