RSA加密

RSA公开密匙密码体制。所谓的公开密钥密码体制就是使用不同的加密密钥与解密密钥,是一种“由已知加密密钥推导出解密密钥在计算上是不可行的”密码体制。

 

在公开密匙密码体制中,加密密钥(即公开密钥)PK是公开信息,而解密密钥(即秘密密钥)SK是需要保密的。加密算法 E和解密算法D也都是公开的。虽然秘密密钥SK是由公开密钥PK决定的,但却不能根据PK计算出SK。正是基于这种理论,1978年出现了著名的RSA算法,它通常是先生成一对RSA 密钥,其中之一是保密密钥,由用户保存;另一个为公开密钥,可对外公开,甚至可在网络服务器中注册。为提高保密强度,RSA密钥至少为500位长,一般推荐使用1024位。这就使加密的计算量很大。为减少计算量,在传送信息时,常采用传统加密方法与公开密钥加密方法相结合的方式,即信息采用改进的DES或IDEA对话密钥加密,然后使用RSA密钥加密对话密钥和信息摘要。对方收到信息后,用不同的密钥解密并可核对信息摘要。

 

RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作。RSA是被研究得最广泛的公匙算法,从提出到现在的三十多年里,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一。

 

当然也有它的不足之处,具体可以询问度娘、谷歌。下面看一下代码中如何使用

 

package com.goma.edcrypt.util;

import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

public class RSAUtil {
	public static void main(String[] args) throws NoSuchAlgorithmException,
			IOException, ClassNotFoundException {
		KeyPair pair = generateKeyPair();
		PrivateKey privateKey = pair.getPrivate();
		PublicKey publicKey = pair.getPublic();

		String en_rsa_str = encrypt("O",publicKey);
		System.out.println("EN_RSA_STRING:::"+en_rsa_str);
		String de_rsa_str = decrypt(en_rsa_str,privateKey);
		System.out.println("DE_RSA_STRING:::"+de_rsa_str);

	}

	public static String encrypt(String msg,PublicKey publicKey) throws IOException, ClassNotFoundException {
		
		RSAPublicKey pbk = (RSAPublicKey)publicKey;
		// RSA算法是使用整数进行加密的,在RSA公钥中包含有两个整数信息:e和n。对于明文数字m,计算密文的公式是m的e次方再与n求模。
		BigInteger e = pbk.getPublicExponent();
		BigInteger n = pbk.getModulus();

		// 获取明文的大整数
		byte ptext[] = msg.getBytes("utf-8");
		BigInteger m = new BigInteger(ptext);

		// 加密明文
		BigInteger c = m.modPow(e, n);

        return c.toString();
	}

	public static String decrypt(String msg,PrivateKey privateKey) throws IOException, ClassNotFoundException {

		BigInteger c = new BigInteger(msg);
		RSAPrivateKey prk = (RSAPrivateKey)privateKey;
		
		// 获取私钥的参数d,n
		BigInteger d = prk.getPrivateExponent();
		BigInteger n = prk.getModulus();

		// 解密明文,返回字符串大数字字节数组
		BigInteger m = c.modPow(d, n);

		// 将字符串大数字字节数组转成字符串
        return new String(m.toByteArray(), "utf-8");
	}

	public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
		final int KEY_SIZE = 1024;
		keyPairGen.initialize(KEY_SIZE, new SecureRandom());
		KeyPair keyPair = keyPairGen.genKeyPair();
		return keyPair;
	}
}
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值