加密算法使用(五):RSA使用全过程

RSA是一种非对称加密算法,使用RSA前先生成一对公钥和私钥。

使用公钥加密的数据可以用私钥解密,同样私钥加密的数据也可以用公钥解密,

不同之处在于,私钥加密数据的同时还可以生成一组签名,签名是用来验证数据是否在传输过程中有变动的,使用公钥、签名、以及公钥加密后的数据,就可以验证是否有变动,当然也可以不验证。

代码示例如下,两个main方法:main和main1。加密解密都是针对byte数组的,考虑到我们实际使用的时候大部分场景应该是用字符串来传递数据,所以演示代码中频繁的将byte数组转化为字符串,有些byte数组不是从字符串直接转化来的,直接通过new String的方式转字符串会出现乱码,所以用到了Base64来解决这一问题。

另外,演示代码为了方便看到全过程,基本上没有抽出方法,实际使用的时候建议重构一下。

说明就到此为止,代码如下:

 package testEncrypt;

 import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map; import javax.crypto.Cipher; import org.apache.commons.codec.binary.Base64; /**
*
* @ClassName: TestRsaEncrypt
* @Description: TODO
* @author: liuyx
* @date: 2016年4月28日上午10:20:59
*/
public class TestRsaEncrypt {
public static final String KEY_ALGORITHM = "RSA";
private static final String PUBLIC_KEY = "RSAPublicKey";
private static final String PRIVATE_KEY = "RSAPrivateKey";
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
private static KeyFactory keyFactory = null;
static {
try {
keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//公钥加密 私钥解密
public static void main(String[] args) throws Exception {
//生成密钥对 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(512); KeyPair keyPair = keyPairGen.generateKeyPair(); // 公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map<String, Object> keyMap = new HashMap<String, Object>(2); keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey); String publicKeyStr = getBase64KeyEncodeStrFromKey(publicKey);
String privateKeyStr = getBase64KeyEncodeStrFromKey(privateKey);
System.out.println("公钥:"+publicKeyStr);
System.out.println("私钥:"+privateKeyStr); //数据加密过程演示
System.out.println("公钥加密——私钥解密"); //要加密的数据
String dataStr = "abcdefghhhhhhhopqrst";
System.out.println("要加密的数据:"+dataStr);
byte[] data = dataStr.getBytes(); // 对公钥解密
Key decodePublicKey = getPublicKeyFromBase64KeyEncodeStr(publicKeyStr); // 对数据加密
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, decodePublicKey);
byte[] encodedData = cipher.doFinal(data);
String encodedDataStr = Base64.encodeBase64String(encodedData);
System.out.println("公钥加密后的数据:"+encodedDataStr); //对私钥解密
Key decodePrivateKey = getPrivateKeyFromBase64KeyEncodeStr(privateKeyStr);
cipher.init(Cipher.DECRYPT_MODE, decodePrivateKey);
encodedData = Base64.decodeBase64(encodedDataStr);
byte[] decodedData = cipher.doFinal(encodedData);
String decodedDataStr = new String(decodedData);
System.out.println("私钥解密后的数据:"+decodedDataStr);
} //私钥加密 公钥解密,附带签名验证过程
public static void main1(String[] args) throws Exception {
//生成密钥对 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(512); KeyPair keyPair = keyPairGen.generateKeyPair(); // 公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map<String, Object> keyMap = new HashMap<String, Object>(2); keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey); String publicKeyStr = getBase64KeyEncodeStrFromKey(publicKey);
String privateKeyStr = getBase64KeyEncodeStrFromKey(privateKey);
System.out.println("公钥:"+publicKeyStr);
System.out.println("私钥:"+privateKeyStr); //数据加密过程演示
System.out.println("私钥加密——公钥解密"); //要加密的数据
String dataStr = "abcdefghhhhhhhopqrst1";
System.out.println("要加密的数据:"+dataStr);
byte[] data = dataStr.getBytes(); //对私钥解密
Key decodePrivateKey = getPrivateKeyFromBase64KeyEncodeStr(privateKeyStr);
//对公钥解密
Key decodePublicKey = getPublicKeyFromBase64KeyEncodeStr(publicKeyStr); // 对数据加密
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, decodePrivateKey);
byte[] encodedData = cipher.doFinal(data); //插曲,加密后的数据+私钥,生成签名,验证签名
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign((PrivateKey)decodePrivateKey); //用的是私钥
signature.update(encodedData); //用的是加密后的数据字节数组 //取得签名
String sign = Base64.encodeBase64String((signature.sign())); //初始化验证签名
signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify((PublicKey )decodePublicKey); //用的是公钥
signature.update(encodedData); //用的是加密后的数据字节数组 //实际的验证过程,获取验证结果
boolean ret = signature.verify(Base64.decodeBase64(sign));
System.out.println("验证结果:"+ret);
//插曲结束 String encodedDataStr = Base64.encodeBase64String(encodedData);
System.out.println("私钥加密后的数据:"+encodedDataStr); cipher.init(Cipher.DECRYPT_MODE, decodePublicKey);
encodedData = Base64.decodeBase64(encodedDataStr);
byte[] decodedData = cipher.doFinal(encodedData);
String decodedDataStr = new String(decodedData);
System.out.println("公钥解密后的数据:"+decodedDataStr); } /*
* 获取key的base64加密后的字符串
*/
private static String getBase64KeyEncodeStrFromKey(Key key) {
return Base64.encodeBase64String(key.getEncoded());
} /*
* 获取base64加密后的字符串的原始公钥
*/
private static Key getPublicKeyFromBase64KeyEncodeStr(String keyStr) {
byte[] keyBytes = Base64.decodeBase64(keyStr);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
Key publicKey = null;
try {
publicKey = keyFactory.generatePublic(x509KeySpec);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return publicKey;
} private static Key getPrivateKeyFromBase64KeyEncodeStr(String keyStr) {
byte[] keyBytes = Base64.decodeBase64(keyStr);
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); Key privateKey=null;
try {
privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return privateKey;
}
}
上一篇:一起学爬虫——使用xpath库爬取猫眼电影国内票房榜


下一篇:[CSS]三层嵌套的滑动门