JAVA中的RSA密钥生成及签名验签

RSA密钥生成

生成一个别名为test的私钥和证书,需要按提示输入私钥密码和证书信息,

keytool -genkey -keystore test.p12 -alias test -keyalg RSA -keysize 1024 -storetype pkcs12

导出公钥证书

keytool -export -alias test -keystore test.p12 -file test.crt

@Component
public class RSAEncrypt {

	private static Logger logger = LoggerFactory.getLogger(RSAEncrypt.class);
	private static RSAEncrypt rsaEncrypt;

	@PostConstruct
	private void initPro() throws Exception {
		rsaEncrypt = this;
		rsaEncrypt.hbpayConfig = this.hbpayConfig;
		RSAEncrypt.init();
	}

	/**
	 * 初始化证书
	 * @throws Exception 
	 */
	private static void init() throws Exception {
		getPrivateKey();
		getPublicKey();
	}

	@Autowired
	private HBpayConfig hbpayConfig;

	private static PrivateKey privateKey;

	private static PublicKey publicKey;

	// 从keystore文件中提取私钥 filename:D:\certs\test.p12
	private static PrivateKey getPrivateKey() {
		if(rsaEncrypt.privateKey == null){
			BufferedInputStream bufferedInputStream = null;
			try {
				FileInputStream is = new FileInputStream(rsaEncrypt.hbpayConfig.getPrivateKeyPath());
				bufferedInputStream = new BufferedInputStream(is);
				KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
				char[] passwd = rsaEncrypt.hbpayConfig.getPrivateKeyPwd().toCharArray();
				keystore.load(bufferedInputStream, passwd);
				rsaEncrypt.privateKey = (PrivateKey) keystore.getKey(rsaEncrypt.hbpayConfig.getPrivateKeyAlias(), passwd);
				return rsaEncrypt.privateKey;
			} catch (KeyStoreException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (CertificateException e) {
				e.printStackTrace();
			} catch (UnrecoverableKeyException e) {
				e.printStackTrace();
			} finally {

				try {
					if(bufferedInputStream != null){
						bufferedInputStream.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return null;
		}else{
			return rsaEncrypt.privateKey;
		}

	}

	// 签名
	private static String sign(PrivateKey privateKey, String message) throws Exception {
		Signature sign = Signature.getInstance("SHA1withRSA");
		sign.initSign(privateKey);
		sign.update(message.getBytes("UTF-8"));
		return new String(Base64.getEncoder().encodeToString(sign.sign()));
	}

	// 验签 读取公钥 ,公钥和包提供filename:D:\certs\test.crt
	private static PublicKey getPublicKey() throws Exception {
		if(rsaEncrypt.publicKey == null){
			BufferedInputStream bufferedInputStream = null;
			try {
				CertificateFactory cf = CertificateFactory.getInstance("X.509");
				FileInputStream inStream = new FileInputStream(rsaEncrypt.hbpayConfig.getPublicKeyPath());
				bufferedInputStream = new BufferedInputStream(inStream);
				Certificate cert = cf.generateCertificate(bufferedInputStream);
				rsaEncrypt.publicKey = cert.getPublicKey();
				return rsaEncrypt.publicKey;
			} catch (CertificateException e) {
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					if(bufferedInputStream != null){
						bufferedInputStream.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return null;
		}
		return rsaEncrypt.publicKey;
	}

	// 验签
	public static boolean verify(String message, String signature) throws Exception {
		Signature sign = Signature.getInstance("SHA1withRSA");
		sign.initVerify(rsaEncrypt.publicKey);
		sign.update(message.getBytes("UTF-8"));
		return sign.verify(Base64.getDecoder().decode(signature));
	}

	// 请求报文 签名 message=body
	public static String getSign(String message) {

		logger.info("签名数据:{}",message);
		String sign = null;
		try {
			sign = sign(rsaEncrypt.privateKey, message);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sign;
	}

	// 请求报文 签名 map=body
	public String getSignByMap(LinkedHashMap<String, String> header, LinkedHashMap<String, String> body) {
		String sign = null;
		StringBuilder message = new StringBuilder();
		for (Map.Entry<String, String> entry : header.entrySet()) {
			String value = entry.getValue();
			message.append(value);
		}
		for (Map.Entry<String, String> entry : body.entrySet()) {
			String value = entry.getValue();
			message.append(value);
		}
		try {
			sign = sign(rsaEncrypt.privateKey, message.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sign;
	}
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RSA数字签名是非常重要的加密算法之一,以下是Java实现RSA数字签名的代码示例: ## 数字签名 ```java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.Key; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; public class RSAUtil { private static final String ALGORITHM = "RSA"; private static final String SIGNATURE_ALGORITHM = "SHA1WithRSA"; /** * 从文件加载私钥 * * @param privateKeyFile 私钥文件 * @return 私钥 * @throws Exception */ public static PrivateKey loadPrivateKeyFromFile(File privateKeyFile) throws Exception { FileInputStream fis = new FileInputStream(privateKeyFile); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { bos.write(buffer, 0, len); } fis.close(); bos.close(); byte[] privateKeyBytes = bos.toByteArray(); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); return keyFactory.generatePrivate(pkcs8KeySpec); } /** * 从文件加载公钥 * * @param publicKeyFile 公钥文件 * @return 公钥 * @throws Exception */ public static PublicKey loadPublicKeyFromFile(File publicKeyFile) throws Exception { FileInputStream fis = new FileInputStream(publicKeyFile); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { bos.write(buffer, 0, len); } fis.close(); bos.close(); byte[] publicKeyBytes = bos.toByteArray(); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); return keyFactory.generatePublic(x509KeySpec); } /** * 对数据进行数字签名 * * @param data 数据 * @param privateKey 私钥 * @return 数字签名 * @throws Exception */ public static byte[] sign(byte[] data, PrivateKey privateKey) throws Exception { Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(privateKey); signature.update(data); return signature.sign(); } /** * 验证数字签名 * * @param data 数据 * @param publicKey 公钥 * @param signedData 数字签名 * @return 是否验证通过 * @throws Exception */ public static boolean verify(byte[] data, PublicKey publicKey, byte[] signedData) throws Exception { Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initVerify(publicKey); signature.update(data); return signature.verify(signedData); } } ``` ## 使用示例 ```java import java.io.File; import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.security.PublicKey; public class Main { public static void main(String[] args) throws Exception { // 加载私钥 File privateKeyFile = new File("private_key.txt"); PrivateKey privateKey = RSAUtil.loadPrivateKeyFromFile(privateKeyFile); // 加载公钥 File publicKeyFile = new File("public_key.txt"); PublicKey publicKey = RSAUtil.loadPublicKeyFromFile(publicKeyFile); // 待签名数据 String data = "Hello, World!"; byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); // 数字签名 byte[] signedData = RSAUtil.sign(dataBytes, privateKey); // 验证数字签名 boolean verified = RSAUtil.verify(dataBytes, publicKey, signedData); System.out.println("Verified: " + verified); } } ``` 以上代码示例,我们使用了`RSAUtil`类的`loadPrivateKeyFromFile`方法和`loadPublicKeyFromFile`方法分别从私钥文件和公钥文件加载私钥和公钥。然后我们使用`sign`方法对待签名数据进行数字签名,使用`verify`方法对签名结果进行验证。 切记,要使用自己的密钥对,不要使用他人的密钥对。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值