RSA加密及验签总结

RSA的数学基础是欧拉函数,它的安全性的保障是大质因数分解十分困难。使用RSA方式时,会首先使用一些工具生成一对公钥和私钥(linux和window下都有),其中,使用私钥可以很快算出公钥,但是使用公钥很难算出私钥。
加密和签名

加密与签名虽然都会使用RSA的一些算法,但是这两个不能混为一谈,是不一样的(主要体现在用途不一样)。加密的作用是为了防止明文内容被人看到,验签是为了防止明文内容被人篡改。
加密

公钥和私钥都能用来加密和解密,通常情况下使用私钥加密,公钥解密。私钥和公钥是成对匹配的,完全匹配的时候才能正确的解密出明文,否则不能获取到正确的密文,所以私钥公钥都能用来加密和解密。不过大多数情况下都是用公钥加密然后用私钥解密,这样能保证能保证明文只能被私钥持有者获取到了。反过来私钥加密公钥公钥解密的话,那么所有持有公钥的人都能获取明文了(这样还要维护公钥的持有者,就麻烦了)。

加密代码:

private static byte[] encrypt(Key key, byte[] data) throws Exception {
	try {
		Cipher cipher = Cipher.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider());
		cipher.init(Cipher.ENCRYPT_MODE, key);
		int blockSize = cipher.getBlockSize();
		int outputSize = cipher.getOutputSize(data.length);
		int leavedSize = data.length % blockSize;
		int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
				: data.length / blockSize;
		byte[] raw = new byte[outputSize * blocksSize];
		int i = 0;
		while (data.length - i * blockSize > 0) {
			if (data.length - i * blockSize > blockSize)
				cipher.doFinal(data, i * blockSize, blockSize, raw, i
						* outputSize);
			else
				cipher.doFinal(data, i * blockSize, data.length - i
						* blockSize, raw, i * outputSize);
			i++;
		}
		return raw;
	} catch (Exception e) {
		throw e;
	}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

解密代码:

private static byte[] decrypt(Key key, byte[] raw) throws Exception {
	try {
		Cipher cipher = Cipher.getInstance("RSA",
				new org.bouncycastle.jce.provider.BouncyCastleProvider());
		cipher.init(Cipher.DECRYPT_MODE, key);
		int blockSize = cipher.getBlockSize();
		ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
		int j = 0;

		while (raw.length - j * blockSize > 0) {
			bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
			j++;
		}
		return bout.toByteArray();
	} catch (Exception e) {
		throw e;
	}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

验签

签名的作用主要就是防止消息内容被篡改,一般是使用私钥生成签名,然后使用公钥验签(信息的发送者一般是私钥的持有者,公钥的持有者接受消息并验证消息是否被篡改)。实现过程是对消息结合私钥,使用sha1、md5等不可逆的散列算法生成签名,然后用公钥对消息签名进行验签。

私钥签名:

public static String signByPrivateKey(PrivateKey privateKey, byte[] data) throws Exception {
	Signature rsa = Signature.getInstance("SHA1withRSA");
	rsa.initSign(privateKey);
	rsa.update(data);
	return new BASE64Encoder().encodeBuffer(rsa.sign());
}

1
2
3
4
5
6

公钥验签:

public static boolean verifyByPublicKey(PublicKey publicKey,byte[] data, String signData) throws Exception {
	boolean verifyFlag = false;
	Signature rsa = Signature.getInstance("SHA1withRSA");
	rsa.initVerify(publicKey);
	rsa.update(data);
	verifyFlag = rsa.verify(new BASE64Decoder().decodeBuffer(signData));
	return verifyFlag;}

猜你喜欢

转载自blog.csdn.net/weixin_43642131/article/details/88788425