当前位置: 代码网 > it编程>编程语言>Java > 前端RSA加密java后端解密示例代码

前端RSA加密java后端解密示例代码

2024年11月25日 Java 我要评论
1. 说明1.rsa是非对称加密。2.前端采用公钥加密,后端采用私钥解密。3.此示例是前端加密,后端解密,后端返回的数据未加密。如果后端相应数据也要加密,可以另写注解,采用对称加密。4.公钥私钥的ba

1. 说明

  • 1.rsa是非对称加密。
  • 2.前端采用公钥加密,后端采用私钥解密。
  • 3.此示例是前端加密,后端解密,后端返回的数据未加密。如果后端相应数据也要加密,可以另写注解,采用对称加密。
  • 4.公钥私钥的base64格式可以由rsautil工具类生成,参考其中main方法。
  • 5.在需要加密的接口上添加自定义注解@apidecryptrsa即可解密。
  • 5.apidecryptparamresolver是解析requestparam参数的,这里没写全,需要额外写注解。

2. 前端示例

  • 1.rsa依赖包
npm install jsencrypt
  • 2.页面代码
<template>
  <el-button type="primary" icon="el-icon-plus" @click="handletest">测试</el-button>
</template>

<script>
import { save } from "@/api/test";
import jsencrypt from 'jsencrypt/bin/jsencrypt.min';
export default {
  name: '测试rsa加密',
  methods: {
    handletest(){
      const crypt = new jsencrypt()
      // 公钥,由后端接口返回,这里写死作为测试
      const publickey = 'migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqcjlmkqsma28rt/bsbj2hdedvbilevnj2fg0gm1++rxxxnebvgycnwndxvztjshtbootadeb1d73dvfckzcj5le/wv21llvrig1baem3zseywpkqzw/5zhc3boddx8vufe3r1kxunqdxhm/67tnc/vms85xgtcbkcfaxcjzyne5rqidaqab';
      crypt.setpublickey(publickey)
      const data = {
        "content": "测试",
      }
      const encrypted = crypt.encrypt(json.stringify(data))
      console.log(encrypted)
      // 调用接口
      save(encrypted).then(res=>{
        console.log(res.data)
      })
    },
  }
}
</script>
  • 3.api请求
import request from "@/axios";

export const save = row => {
  return request({
    url: '/xapi/test/save',
    headers: {
      'content-type': 'text/plain'
    },
    method: 'post',
    data: row,
  });
};

3. 后端示例

3.1 pom依赖

  • 1.pom依赖
<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/pom/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
         xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelversion>4.0.0</modelversion>

    <groupid>org.example</groupid>
    <artifactid>my-springboot</artifactid>
    <version>1.0-snapshot</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <parent>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-parent</artifactid>
        <version>2.7.6</version>
    </parent>

    <dependencies>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-autoconfigure</artifactid>
        </dependency>
        <dependency>
            <groupid>org.springframework</groupid>
            <artifactid>spring-core</artifactid>
        </dependency>
        <dependency>
            <groupid>com.alibaba</groupid>
            <artifactid>fastjson</artifactid>
            <version>2.0.40</version>
        </dependency>
        <dependency>
            <groupid>com.fasterxml.jackson.core</groupid>
            <artifactid>jackson-databind</artifactid>
            <version>2.13.0</version>
        </dependency>
        <dependency>
            <groupid>org.projectlombok</groupid>
            <artifactid>lombok</artifactid>
        </dependency>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-autoconfigure</artifactid>
        </dependency>
    </dependencies>
</project>

3.2 后端结构图

  • 2.后端结构图

3.3 decrypthttpinputmessage

  • 3.decrypthttpinputmessage
package com.learning.bean;

import lombok.getter;
import lombok.requiredargsconstructor;
import org.springframework.http.httpheaders;
import org.springframework.http.httpinputmessage;

import java.io.inputstream;

/**
 * <p>解密信息输入流</p>
 *
 */
@getter
@requiredargsconstructor
public class decrypthttpinputmessage implements httpinputmessage {
	private final inputstream body;
	private final httpheaders headers;
}

3.4 apicryptoproperties

  • 4.apicryptoproperties
package com.learning.config;

import com.learning.crypto.advice.apidecryptparamresolver;
import com.learning.crypto.props.apicryptoproperties;
import lombok.requiredargsconstructor;
import org.springframework.boot.autoconfigure.autoconfiguration;
import org.springframework.boot.autoconfigure.condition.conditionalonproperty;
import org.springframework.boot.context.properties.enableconfigurationproperties;
import org.springframework.web.method.support.handlermethodargumentresolver;
import org.springframework.web.servlet.config.annotation.webmvcconfigurer;

import java.util.list;

/**
 * api 签名自动配置
 *
 */
@autoconfiguration
@requiredargsconstructor
@enableconfigurationproperties(apicryptoproperties.class)
@conditionalonproperty(value = apicryptoproperties.prefix + ".enabled", havingvalue = "true", matchifmissing = true)
public class apicryptoconfiguration implements webmvcconfigurer {
	private final apicryptoproperties apicryptoproperties;

	@override
	public void addargumentresolvers(list<handlermethodargumentresolver> argumentresolvers) {
		argumentresolvers.add(new apidecryptparamresolver(apicryptoproperties));
	}

}

3.5 testcontroller

  • 5.testcontroller
package com.learning.controller;

import com.learning.crypto.annotation.apidecryptrsa;
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.requestbody;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;

@restcontroller
@requestmapping("/test")
public class testcontroller {
    @postmapping(value = "/save", produces = "text/plain")
    @apidecryptrsa
    public string save(@requestbody string data){
        return data;
    }
}

3.6 apicryptoutil

  • 6.apicryptoutil
package com.learning.crypto.advice;

import com.learning.crypto.props.apicryptoproperties;

import java.util.objects;
import com.learning.util.rsautil;
/**
 * <p>辅助工具类</p>
 *
 */
public class apicryptoutil {

	/**
	 * 选择加密方式并进行解密
	 *
	 * @param bodydata byte array
	 * @return 解密结果
	 */
	public static byte[] decryptdata(apicryptoproperties properties, byte[] bodydata) {
		string privatekey = objects.requirenonnull(properties.getrsaprivatekey());
		return rsautil.decryptfrombase64(privatekey, bodydata);
	}

}

3.7 apidecryptparamresolver

  • 7.apidecryptparamresolver
package com.learning.crypto.advice;

import com.fasterxml.jackson.databind.objectmapper;
import com.learning.crypto.annotation.apidecryptrsa;
import com.learning.crypto.props.apicryptoproperties;
import com.learning.util.func;
import lombok.requiredargsconstructor;
import org.springframework.core.methodparameter;
import org.springframework.core.annotation.annotatedelementutils;
import org.springframework.lang.nullable;
import org.springframework.web.bind.support.webdatabinderfactory;
import org.springframework.web.context.request.nativewebrequest;
import org.springframework.web.method.support.handlermethodargumentresolver;
import org.springframework.web.method.support.modelandviewcontainer;

import java.lang.reflect.parameter;
import java.nio.charset.standardcharsets;

/**
 * param 参数 解析
 *
 */
@requiredargsconstructor
public class apidecryptparamresolver implements handlermethodargumentresolver {
	private final apicryptoproperties properties;

	@override
	public boolean supportsparameter(methodparameter parameter) {
		return annotatedelementutils.hasannotation(parameter.getparameter(), apidecryptrsa.class);
	}

	@nullable
	@override
	public object resolveargument(methodparameter methodparameter, modelandviewcontainer mavcontainer,
								  nativewebrequest webrequest, webdatabinderfactory binderfactory) {
		parameter parameter = methodparameter.getparameter();
		string text = webrequest.getparameter(properties.getparamname());
		if (func.isempty(text)) {
			return null;
		}
		byte[] textbytes = text.getbytes(standardcharsets.utf_8);
		byte[] decryptdata = apicryptoutil.decryptdata(properties, textbytes);
		objectmapper mapper = new objectmapper();
		try{
			return mapper.readvalue(decryptdata, parameter.gettype());
		}catch (exception e){
			e.printstacktrace();
			return null;
		}
	}
}

3.8 apidecryptrequestbodyadvice

  • 8.apidecryptrequestbodyadvice
package com.learning.crypto.advice;

import com.learning.crypto.annotation.apidecryptrsa;
import com.learning.crypto.props.apicryptoproperties;
import com.learning.util.classutil;
import com.learning.bean.decrypthttpinputmessage;
import lombok.requiredargsconstructor;
import lombok.extern.slf4j.slf4j;
import org.springframework.boot.autoconfigure.autoconfiguration;
import org.springframework.boot.autoconfigure.condition.conditionalonproperty;
import org.springframework.core.methodparameter;
import org.springframework.core.annotation.order;
import org.springframework.http.httpinputmessage;
import org.springframework.http.converter.httpmessageconverter;
import org.springframework.lang.nonnull;
import org.springframework.util.streamutils;
import org.springframework.web.bind.annotation.controlleradvice;
import org.springframework.web.servlet.mvc.method.annotation.requestbodyadvice;

import java.io.bytearrayinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.lang.reflect.type;

/**
 * 请求数据的加密信息解密处理<br>
 * 本类只对控制器参数中含有<strong>{@link org.springframework.web.bind.annotation.requestbody}</strong>
 * 以及package为<strong><code>ccom.xiaoi.xics.core.crypto.api.signature.annotation.decrypt</code></strong>下的注解有效
 */
@slf4j
@order(1)
@autoconfiguration
@controlleradvice
@requiredargsconstructor
@conditionalonproperty(value = apicryptoproperties.prefix + ".enabled", havingvalue = "true", matchifmissing = true)
public class apidecryptrequestbodyadvice implements requestbodyadvice {
	private final apicryptoproperties properties;

	@override
	public boolean supports(methodparameter methodparameter, @nonnull type targettype, @nonnull class<? extends httpmessageconverter<?>> convertertype) {
		return classutil.isannotated(methodparameter.getmethod(), apidecryptrsa.class);
	}

	@override
	public object handleemptybody(object body, @nonnull httpinputmessage inputmessage, @nonnull methodparameter parameter, @nonnull type targettype, @nonnull class<? extends httpmessageconverter<?>> convertertype) {
		return body;
	}

	@nonnull
	@override
	public httpinputmessage beforebodyread(httpinputmessage inputmessage, @nonnull methodparameter parameter, @nonnull type targettype, @nonnull class<? extends httpmessageconverter<?>> convertertype) throws ioexception {
		// 判断 body 是否为空
		inputstream messagebody = inputmessage.getbody();
		if (messagebody.available() <= 0) {
			return inputmessage;
		}
		byte[] decryptedbody = null;
		byte[] bodybytearray = streamutils.copytobytearray(messagebody);
		decryptedbody = apicryptoutil.decryptdata(properties, bodybytearray);
		if (decryptedbody == null) {
			throw new runtimeexception("decryption error, " +
				"please check if the selected source data is encrypted correctly." +
				" (解密错误,请检查选择的源数据的加密方式是否正确。)");
		}
		inputstream inputstream = new bytearrayinputstream(decryptedbody);
		return new decrypthttpinputmessage(inputstream, inputmessage.getheaders());
	}

	@nonnull
	@override
	public object afterbodyread(@nonnull object body, @nonnull httpinputmessage inputmessage, @nonnull methodparameter parameter, @nonnull type targettype, @nonnull class<? extends httpmessageconverter<?>> convertertype) {
		return body;
	}

}

3.9 apidecryptrsa

  • 9.apidecryptrsa
package com.learning.crypto.annotation;

import java.lang.annotation.*;

/**
 * rsa 解密
 */
@target({elementtype.type, elementtype.method, elementtype.parameter})
@retention(retentionpolicy.runtime)
@documented
@inherited
public @interface apidecryptrsa {
}

3.10 apicryptoproperties

  • 10.apicryptoproperties
package com.learning.crypto.props;

import lombok.getter;
import lombok.setter;
import org.springframework.boot.context.properties.configurationproperties;

/**
 * api 签名配置类
 */
@getter
@setter
@configurationproperties(apicryptoproperties.prefix)
public class apicryptoproperties {
	/**
	 * 前缀
	 */
	public static final string prefix = "api.crypto";

	/**
	 * 是否开启 api 签名
	 */
	private boolean enabled = boolean.true;

	/**
	 * url的参数签名,传递的参数名。例如:/user?data=签名后的数据
	 */
	private string paramname = "data";

	/**
	 * rsa 私钥
	 */
	private string rsaprivatekey;

}

3.11 keypair

  • 11.keypair
package com.learning.crypto.tuple;

import com.learning.util.rsautil;
import lombok.requiredargsconstructor;

import java.security.privatekey;
import java.security.publickey;

/**
 * rsa 的 key pair 封装
 *
 */
@requiredargsconstructor
public class keypair {
	private final java.security.keypair keypair;

	public publickey getpublic() {
		return keypair.getpublic();
	}

	public privatekey getprivate() {
		return keypair.getprivate();
	}

	public byte[] getpublicbytes() {
		return this.getpublic().getencoded();
	}

	public byte[] getprivatebytes() {
		return this.getprivate().getencoded();
	}

	public string getpublicbase64() {
		return rsautil.getkeystring(this.getpublic());
	}

	public string getprivatebase64() {
		return rsautil.getkeystring(this.getprivate());
	}

	@override
	public string tostring() {
		return "publickey=" + this.getpublicbase64() + '\n' + "privatekey=" + this.getprivatebase64();
	}
}

3.12 pair

  • 12.pair
package com.learning.crypto.tuple;

import lombok.equalsandhashcode;
import lombok.getter;
import lombok.tostring;

/**
 * tuple pair
 **/
@getter
@tostring
@equalsandhashcode
public class pair<l, r> {
	private static final pair<object, object> empty = new pair<>(null, null);

	private final l left;
	private final r right;

	/**
	 * returns an empty pair.
	 */
	@suppresswarnings("unchecked")
	public static <l, r> pair<l, r> empty() {
		return (pair<l, r>) empty;
	}

	/**
	 * constructs a pair with its left value being {@code left}, or returns an empty pair if
	 * {@code left} is null.
	 *
	 * @return the constructed pair or an empty pair if {@code left} is null.
	 */
	public static <l, r> pair<l, r> createleft(l left) {
		if (left == null) {
			return empty();
		} else {
			return new pair<>(left, null);
		}
	}

	/**
	 * constructs a pair with its right value being {@code right}, or returns an empty pair if
	 * {@code right} is null.
	 *
	 * @return the constructed pair or an empty pair if {@code right} is null.
	 */
	public static <l, r> pair<l, r> createright(r right) {
		if (right == null) {
			return empty();
		} else {
			return new pair<>(null, right);
		}
	}

	public static <l, r> pair<l, r> create(l left, r right) {
		if (right == null && left == null) {
			return empty();
		} else {
			return new pair<>(left, right);
		}
	}

	private pair(l left, r right) {
		this.left = left;
		this.right = right;
	}

}

3.13 classutil

  • 13.classutil
package com.learning.util;

import org.springframework.core.bridgemethodresolver;
import org.springframework.core.defaultparameternamediscoverer;
import org.springframework.core.methodparameter;
import org.springframework.core.parameternamediscoverer;
import org.springframework.core.annotation.annotatedelementutils;
import org.springframework.core.annotation.synthesizingmethodparameter;
import org.springframework.web.method.handlermethod;

import java.lang.annotation.annotation;
import java.lang.reflect.constructor;
import java.lang.reflect.method;

/**
 * 类操作工具
 */
public class classutil extends org.springframework.util.classutils {

	private static final parameternamediscoverer parameter_name_discoverer = new defaultparameternamediscoverer();

	/**
	 * 获取方法参数信息
	 *
	 * @param constructor    构造器
	 * @param parameterindex 参数序号
	 * @return {methodparameter}
	 */
	public static methodparameter getmethodparameter(constructor<?> constructor, int parameterindex) {
		methodparameter methodparameter = new synthesizingmethodparameter(constructor, parameterindex);
		methodparameter.initparameternamediscovery(parameter_name_discoverer);
		return methodparameter;
	}

	/**
	 * 获取方法参数信息
	 *
	 * @param method         方法
	 * @param parameterindex 参数序号
	 * @return {methodparameter}
	 */
	public static methodparameter getmethodparameter(method method, int parameterindex) {
		methodparameter methodparameter = new synthesizingmethodparameter(method, parameterindex);
		methodparameter.initparameternamediscovery(parameter_name_discoverer);
		return methodparameter;
	}

	/**
	 * 获取annotation
	 *
	 * @param method         method
	 * @param annotationtype 注解类
	 * @param <a>            泛型标记
	 * @return {annotation}
	 */
	public static <a extends annotation> a getannotation(method method, class<a> annotationtype) {
		class<?> targetclass = method.getdeclaringclass();
		// the method may be on an interface, but we need attributes from the target class.
		// if the target class is null, the method will be unchanged.
		method specificmethod = classutil.getmostspecificmethod(method, targetclass);
		// if we are dealing with method with generic parameters, find the original method.
		specificmethod = bridgemethodresolver.findbridgedmethod(specificmethod);
		// 先找方法,再找方法上的类
		a annotation = annotatedelementutils.findmergedannotation(specificmethod, annotationtype);
		;
		if (null != annotation) {
			return annotation;
		}
		// 获取类上面的annotation,可能包含组合注解,故采用spring的工具类
		return annotatedelementutils.findmergedannotation(specificmethod.getdeclaringclass(), annotationtype);
	}

	/**
	 * 获取annotation
	 *
	 * @param handlermethod  handlermethod
	 * @param annotationtype 注解类
	 * @param <a>            泛型标记
	 * @return {annotation}
	 */
	public static <a extends annotation> a getannotation(handlermethod handlermethod, class<a> annotationtype) {
		// 先找方法,再找方法上的类
		a annotation = handlermethod.getmethodannotation(annotationtype);
		if (null != annotation) {
			return annotation;
		}
		// 获取类上面的annotation,可能包含组合注解,故采用spring的工具类
		class<?> beantype = handlermethod.getbeantype();
		return annotatedelementutils.findmergedannotation(beantype, annotationtype);
	}


	/**
	 * 判断是否有注解 annotation
	 *
	 * @param method         method
	 * @param annotationtype 注解类
	 * @param <a>            泛型标记
	 * @return {boolean}
	 */
	public static <a extends annotation> boolean isannotated(method method, class<a> annotationtype) {
		// 先找方法,再找方法上的类
		boolean ismethodannotated = annotatedelementutils.isannotated(method, annotationtype);
		if (ismethodannotated) {
			return true;
		}
		// 获取类上面的annotation,可能包含组合注解,故采用spring的工具类
		class<?> targetclass = method.getdeclaringclass();
		return annotatedelementutils.isannotated(targetclass, annotationtype);
	}

}

3.14 func

  • 14.func
package com.learning.util;

import org.springframework.lang.nullable;
import org.springframework.util.objectutils;

/**
 * 工具类
 */
public class func {


	/**
	 * 判断空对象 object、map、list、set、字符串、数组
	 *
	 * @param obj the object to check
	 * @return 数组是否为空
	 */
	public static boolean isempty(@nullable object obj) {
		return objectutils.isempty(obj);
	}

	/**
	 * 对象不为空 object、map、list、set、字符串、数组
	 *
	 * @param obj the object to check
	 * @return 是否不为空
	 */
	public static boolean isnotempty(@nullable object obj) {
		return !objectutils.isempty(obj);
	}

}

3.15 rsautil

  • 15.rsautil
package com.learning.util;

import com.learning.crypto.tuple.keypair;
import org.springframework.lang.nullable;
import org.springframework.util.base64utils;

import javax.crypto.cipher;
import java.math.biginteger;
import java.nio.charset.standardcharsets;
import java.security.*;
import java.security.spec.*;
import java.util.objects;

/**
 * rsa加、解密工具
 *
 * 1. 公钥负责加密,私钥负责解密;
 * 2. 私钥负责签名,公钥负责验证。
 */
public class rsautil {
	/**
	 * 数字签名,密钥算法
	 */
	public static final string rsa_algorithm = "rsa";
	public static final string rsa_padding = "rsa/ecb/pkcs1padding";

	/**
	 * 获取 keypair
	 *
	 * @return keypair
	 */
	public static keypair genkeypair() {
		return genkeypair(1024);
	}

	/**
	 * 获取 keypair
	 *
	 * @param keysize key size
	 * @return keypair
	 */
	public static keypair genkeypair(int keysize) {
		try {
			keypairgenerator keypairgen = keypairgenerator.getinstance(rsa_algorithm);
			// 密钥位数
			keypairgen.initialize(keysize);
			// 密钥对
			return new keypair(keypairgen.generatekeypair());
		} catch (exception e) {
			throw new runtimeexception(e);
		}
	}

	/**
	 * 生成rsa私钥
	 *
	 * @param modulus n特征值
	 * @param exponent d特征值
	 * @return {@link privatekey}
	 */
	public static privatekey generateprivatekey(string modulus, string exponent) {
		return generateprivatekey(new biginteger(modulus), new biginteger(exponent));
	}

	/**
	 * 生成rsa私钥
	 *
	 * @param modulus n特征值
	 * @param exponent d特征值
	 * @return {@link privatekey}
	 */
	public static privatekey generateprivatekey(biginteger modulus, biginteger exponent) {
		rsaprivatekeyspec keyspec = new rsaprivatekeyspec(modulus, exponent);
		try {
			keyfactory keyfactory = keyfactory.getinstance(rsa_algorithm);
			return keyfactory.generateprivate(keyspec);
		} catch (exception e) {
			throw new runtimeexception(e);
		}
	}

	/**
	 * 生成rsa公钥
	 *
	 * @param modulus n特征值
	 * @param exponent e特征值
	 * @return {@link publickey}
	 */
	public static publickey generatepublickey(string modulus, string exponent) {
		return generatepublickey(new biginteger(modulus), new biginteger(exponent));
	}

	/**
	 * 生成rsa公钥
	 *
	 * @param modulus n特征值
	 * @param exponent e特征值
	 * @return {@link publickey}
	 */
	public static publickey generatepublickey(biginteger modulus, biginteger exponent) {
		rsapublickeyspec keyspec = new rsapublickeyspec(modulus, exponent);
		try {
			keyfactory keyfactory = keyfactory.getinstance(rsa_algorithm);
			return keyfactory.generatepublic(keyspec);
		} catch (exception e) {
			throw new runtimeexception(e);
		}
	}

	/**
	 * 得到公钥
	 *
	 * @param base64pubkey 密钥字符串(经过base64编码)
	 * @return publickey
	 */
	public static publickey getpublickey(string base64pubkey) {
		objects.requirenonnull(base64pubkey, "base64 public key is null.");
		byte[] keybytes = base64utils.decodefromstring(base64pubkey);
		x509encodedkeyspec keyspec = new x509encodedkeyspec(keybytes);
		try {
			keyfactory keyfactory = keyfactory.getinstance(rsa_algorithm);
			return keyfactory.generatepublic(keyspec);
		} catch (exception e) {
			throw new runtimeexception(e);
		}
	}

	/**
	 * 得到公钥字符串
	 *
	 * @param base64pubkey 密钥字符串(经过base64编码)
	 * @return publickey string
	 */
	public static string getpublickeytobase64(string base64pubkey) {
		publickey publickey = getpublickey(base64pubkey);
		return getkeystring(publickey);
	}

	/**
	 * 得到私钥
	 *
	 * @param base64prikey 密钥字符串(经过base64编码)
	 * @return privatekey
	 */
	public static privatekey getprivatekey(string base64prikey) {
		objects.requirenonnull(base64prikey, "base64 private key is null.");
		byte[] keybytes = base64utils.decodefromstring(base64prikey);
		pkcs8encodedkeyspec keyspec = new pkcs8encodedkeyspec(keybytes);
		try {
			keyfactory keyfactory = keyfactory.getinstance(rsa_algorithm);
			return keyfactory.generateprivate(keyspec);
		} catch (nosuchalgorithmexception | invalidkeyspecexception e) {
			throw new runtimeexception(e);
		}
	}

	/**
	 * 得到密钥字符串(经过base64编码)
	 *
	 * @param key key
	 * @return base 64 编码后的 key
	 */
	public static string getkeystring(key key) {
		return base64utils.encodetostring(key.getencoded());
	}

	/**
	 * 得到私钥 base64
	 *
	 * @param base64prikey 密钥字符串(经过base64编码)
	 * @return privatekey string
	 */
	public static string getprivatekeytobase64(string base64prikey) {
		privatekey privatekey = getprivatekey(base64prikey);
		return getkeystring(privatekey);
	}

	/**
	 * 共要加密
	 *
	 * @param base64publickey base64 的公钥
	 * @param data            待加密的内容
	 * @return 加密后的内容
	 */
	public static byte[] encrypt(string base64publickey, byte[] data) {
		return encrypt(getpublickey(base64publickey), data);
	}

	/**
	 * 共要加密
	 *
	 * @param publickey 公钥
	 * @param data      待加密的内容
	 * @return 加密后的内容
	 */
	public static byte[] encrypt(publickey publickey, byte[] data) {
		return rsa(publickey, data, cipher.encrypt_mode);
	}

	/**
	 * 私钥加密,用于 qpp 内,公钥解密
	 *
	 * @param base64privatekey base64 的私钥
	 * @param data             待加密的内容
	 * @return 加密后的内容
	 */
	public static byte[] encryptbyprivatekey(string base64privatekey, byte[] data) {
		return encryptbyprivatekey(getprivatekey(base64privatekey), data);
	}

	/**
	 * 私钥加密,加密成 base64 字符串,用于 qpp 内,公钥解密
	 *
	 * @param base64privatekey base64 的私钥
	 * @param data             待加密的内容
	 * @return 加密后的内容
	 */
	public static string encryptbyprivatekeytobase64(string base64privatekey, byte[] data) {
		return base64utils.encodetostring(encryptbyprivatekey(base64privatekey, data));
	}

	/**
	 * 私钥加密,用于 qpp 内,公钥解密
	 *
	 * @param privatekey 私钥
	 * @param data       待加密的内容
	 * @return 加密后的内容
	 */
	public static byte[] encryptbyprivatekey(privatekey privatekey, byte[] data) {
		return rsa(privatekey, data, cipher.encrypt_mode);
	}

	/**
	 * 公钥加密
	 *
	 * @param base64publickey base64 公钥
	 * @param data            待加密的内容
	 * @return 加密后的内容
	 */
	@nullable
	public static string encrypttobase64(string base64publickey, @nullable string data) {
		if (func.isempty(data)) {
			return null;
		}
		return base64utils.encodetostring(encrypt(base64publickey, data.getbytes(standardcharsets.utf_8)));
	}

	/**
	 * 解密
	 *
	 * @param base64privatekey base64 私钥
	 * @param data             数据
	 * @return 解密后的数据
	 */
	public static byte[] decrypt(string base64privatekey, byte[] data) {
		return decrypt(getprivatekey(base64privatekey), data);
	}

	/**
	 * 解密
	 *
	 * @param base64publickey base64 公钥
	 * @param data            数据
	 * @return 解密后的数据
	 */
	public static byte[] decryptbypublickey(string base64publickey, byte[] data) {
		return decryptbypublickey(getpublickey(base64publickey), data);
	}

	/**
	 * 解密
	 *
	 * @param privatekey privatekey
	 * @param data       数据
	 * @return 解密后的数据
	 */
	public static byte[] decrypt(privatekey privatekey, byte[] data) {
		return rsa(privatekey, data, cipher.decrypt_mode);
	}

	/**
	 * 解密
	 *
	 * @param publickey publickey
	 * @param data      数据
	 * @return 解密后的数据
	 */
	public static byte[] decryptbypublickey(publickey publickey, byte[] data) {
		return rsa(publickey, data, cipher.decrypt_mode);
	}

	/**
	 * rsa 加、解密
	 *
	 * @param key  key
	 * @param data 数据
	 * @param mode 模式
	 * @return 解密后的数据
	 */
	private static byte[] rsa(key key, byte[] data, int mode) {
		try {
			cipher cipher = cipher.getinstance(rsa_padding);
			cipher.init(mode, key);
			return cipher.dofinal(data);
		} catch (exception e) {
			throw new runtimeexception(e);
		}
	}

	/**
	 * base64 数据解密
	 *
	 * @param base64publickey base64 公钥
	 * @param base64data      base64数据
	 * @return 解密后的数据
	 */
	public static byte[] decryptbypublickeyfrombase64(string base64publickey, byte[] base64data) {
		return decryptbypublickey(getpublickey(base64publickey), base64data);
	}

	/**
	 * base64 数据解密
	 *
	 * @param base64privatekey base64 私钥
	 * @param base64data       base64数据
	 * @return 解密后的数据
	 */
	@nullable
	public static string decryptfrombase64(string base64privatekey, @nullable string base64data) {
		if (func.isempty(base64data)) {
			return null;
		}
		return new string(decrypt(base64privatekey, base64utils.decodefromstring(base64data)), standardcharsets.utf_8);
	}

	/**
	 * base64 数据解密
	 *
	 * @param base64privatekey base64 私钥
	 * @param base64data       base64数据
	 * @return 解密后的数据
	 */
	public static byte[] decryptfrombase64(string base64privatekey, byte[] base64data) {
		return decrypt(base64privatekey, base64utils.decode(base64data));
	}

	/**
	 * base64 数据解密
	 *
	 * @param base64publickey base64 公钥
	 * @param base64data      base64数据
	 * @return 解密后的数据
	 */
	@nullable
	public static string decryptbypublickeyfrombase64(string base64publickey, @nullable string base64data) {
		if (func.isempty(base64data)) {
			return null;
		}
		return new string(decryptbypublickeyfrombase64(base64publickey, base64utils.decodefromstring(base64data)), standardcharsets.utf_8);
	}

	public static void main(string[] args) {
//		keypair keypair = genkeypair();
//		system.out.println("私钥:"+keypair.getprivatebase64());
//		system.out.println("公钥:"+keypair.getpublicbase64());
		string privatebase64 = "miicdgibadanbgkqhkig9w0baqefaascamawggjcageaaogbaimwasqyydbyu39uwenaemr29sius+cnz+dscbx76tffc0qg8bikfccpg/o2owe1uii0b14hupvcnv8irmkpkt79a/bwww+uibvsb4zfnitla8pdnb/noelce4n3hy+4v7evurg6ep1ceb/ru2cl9uxlzlca0igrx8bcilni0tmtagmbaaecgybfsllix25f/teh4jl+dws+g9gec991fyjf06ueoul3qnza4sxpjaydvr5yqw9syhzqbmg3v2pwkhtn0cx9zsnf3iydd0eqob0ky9m7qwxifcd0ug1ruc+cb1/vewrrj15vh2qod9jmgezhxwelvx0cenrpemicij+ztt0kvx+uqqjbamecqobg5a5x3lksdgsubltnbeispqh+fla3+3ut29u+s5b9upxhwbwvfrt3gtgjxaftii/lha7wzbfuyrkcxgucqqc2fvxhnsfwteircoimx+wid3filobnpnzgr75yzozjddpdnvhelo2csuatogdsk8s2hcutwi2lsm/yxx9bzjepakeag/fysidike52fxyatzuxizgz8jmiwaysbjkie7iqwsoze6jdtwru/btlp94dpq3f0aqd/yn4mcskh6d9hhch6qjazrdonkj2oyren3i1cz0tnc52eid+prgdqjtwyuov74e/itxbep27bhlyedxq/851glxwa9n6dkr7qikne3ji2qjamcs1ipl0n/ar0nr56/ui0r1cd2asoimfzjc8hpwdjs/yfpzvqnrcpgqx5ps4o631f7lqkz22mbwoobt3uczysq==";
		string publicbase64 = "migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqcjlmkqsma28rt/bsbj2hdedvbilevnj2fg0gm1++rxxxnebvgycnwndxvztjshtbootadeb1d73dvfckzcj5le/wv21llvrig1baem3zseywpkqzw/5zhc3boddx8vufe3r1kxunqdxhm/67tnc/vms85xgtcbkcfaxcjzyne5rqidaqab";
		system.out.println("加密数据:"+encrypttobase64(publicbase64, "hello world"));
		system.out.println("解密数据:"+decryptfrombase64(privatebase64, encrypttobase64(publicbase64, "hello world")));
		string data = "hu5u8uyeg6fcn+/4wkfrsuvgetrxgifve6/rzrbqcvxaqt+xma7c+xvr6ws2zxfmyvfos0yl29u6ovkxvmesdrc9zj/bf0m6ykqa57vyvvrrmrrqcsyud6sto/qrdpfk4sxlssetu2/xjzqyohnrmmouyspwykj3fcn34uoiehc=";
//		system.out.println("解密数据:"+decryptfrombase64(privatebase64, data));
		system.out.println("解密数据:"+rsautil.decryptfrombase64(privatebase64, data));
	}

}

3.16 springbootlearningapplication启动类

  • 16.springbootlearningapplication
package com.learning;

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.context.annotation.componentscan;

/**
 **/
@springbootapplication
@componentscan(basepackages = {"com.learning"})
public class springbootlearningapplication {
    public static void main(string[] args) {
        springapplication.run(springbootlearningapplication.class, args);
    }
}

3.17 配置文件

  • 17.application.yaml
api:
  crypto:
    # 私钥
    rsaprivatekey: miicdgibadanbgkqhkig9w0baqefaascamawggjcageaaogbaimwasqyydbyu39uwenaemr29sius+cnz+dscbx76tffc0qg8bikfccpg/o2owe1uii0b14hupvcnv8irmkpkt79a/bwww+uibvsb4zfnitla8pdnb/noelce4n3hy+4v7evurg6ep1ceb/ru2cl9uxlzlca0igrx8bcilni0tmtagmbaaecgybfsllix25f/teh4jl+dws+g9gec991fyjf06ueoul3qnza4sxpjaydvr5yqw9syhzqbmg3v2pwkhtn0cx9zsnf3iydd0eqob0ky9m7qwxifcd0ug1ruc+cb1/vewrrj15vh2qod9jmgezhxwelvx0cenrpemicij+ztt0kvx+uqqjbamecqobg5a5x3lksdgsubltnbeispqh+fla3+3ut29u+s5b9upxhwbwvfrt3gtgjxaftii/lha7wzbfuyrkcxgucqqc2fvxhnsfwteircoimx+wid3filobnpnzgr75yzozjddpdnvhelo2csuatogdsk8s2hcutwi2lsm/yxx9bzjepakeag/fysidike52fxyatzuxizgz8jmiwaysbjkie7iqwsoze6jdtwru/btlp94dpq3f0aqd/yn4mcskh6d9hhch6qjazrdonkj2oyren3i1cz0tnc52eid+prgdqjtwyuov74e/itxbep27bhlyedxq/851glxwa9n6dkr7qikne3ji2qjamcs1ipl0n/ar0nr56/ui0r1cd2asoimfzjc8hpwdjs/yfpzvqnrcpgqx5ps4o631f7lqkz22mbwoobt3uczysq==

4. 调用截图

总结 

到此这篇关于前端rsa加密java后端解密的文章就介绍到这了,更多相关前端rsa加密后端解密内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com