java RSA公钥加密,私钥解密算法例子.

摘要: RSA 是一种非对称加密算法,一般很难破解,因此一些要求比较高的系统通常会采用rsa加密算法,一般来说用RSA加密有如下几个步骤.1. 生成公钥与私钥2. 用公钥对需要加密的字符串等进行加密3. 在需要解密的地方,用私钥进行解密

RSA 是一种非对称加密算法,一般很难破解,因此一些要求比较高的系统通常会采用rsa加密算法,一般来说用RSA加密有如下几个步骤.
1. 生成公钥与私钥
2. 用公钥对需要加密的字符串等进行加密
3. 在需要解密的地方,用私钥进行解密
下面对上面的几个部分贴出代码.

1. 生成公钥与私钥

package com.rsa;
import java.io.FileOutputStream; 
import java.security.KeyPair; 
import java.security.KeyPairGenerator; 
import java.security.SecureRandom; 
import java.util.Date;

public class GenKeys {
	public static void main(String[] args) throws Exception {
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); 
		SecureRandom secureRandom = new SecureRandom(new Date().toString().getBytes());
		keyPairGenerator.initialize(1024, secureRandom);
		KeyPair keyPair = keyPairGenerator.genKeyPair();
		String publicKeyFilename = "D:/publicKeyFile";
		byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
		FileOutputStream fos = new FileOutputStream(publicKeyFilename); 
		fos.write(publicKeyBytes); 
		fos.close();
		String privateKeyFilename = "D:/privateKeyFile"; 
		byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
		fos = new FileOutputStream(privateKeyFilename); 
		fos.write(privateKeyBytes); 
		fos.close();
	}
}


2. 读取公钥方法
package com.rsa;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.security.KeyFactory;

public class PublicKeyReader {	
	public static PublicKey get(String filename) throws Exception {
		File f = new File(filename);
		FileInputStream fis = new FileInputStream(f); 
		DataInputStream dis = new DataInputStream(fis);
		byte[] keyBytes = new byte[(int)f.length()]; 
		dis.readFully(keyBytes); 
		dis.close();
		X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
		KeyFactory kf = KeyFactory.getInstance("RSA"); 
		return kf.generatePublic(spec);
	}


}



3.读取私钥方法
package com.rsa;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
public class PrivateKeyReader {	
	public static PrivateKey get(String filename)throws Exception {
	    File f = new File(filename);
	    FileInputStream fis = new FileInputStream(f);
	    DataInputStream dis = new DataInputStream(fis);
	    byte[] keyBytes = new byte[(int)f.length()];
	    dis.readFully(keyBytes);
	    dis.close();
	    PKCS8EncodedKeySpec spec =new PKCS8EncodedKeySpec(keyBytes);
	    KeyFactory kf = KeyFactory.getInstance("RSA");
	    return kf.generatePrivate(spec);
	  }
 
	
	public static void main(String[] args) throws Exception, InvalidKeySpecException, IOException {
		PrivateKeyReader.get("d:/privateKeyFile");
	}
}



4. 测试公钥加密,私钥解密
package com.rsa;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;

public class TestEncryptAndDecrypt {	
	public static void main(String[] args) throws Exception {
		String input = "thisIsMyPassword$7788";
		Cipher cipher = Cipher.getInstance("RSA");		
		RSAPublicKey pubKey = (RSAPublicKey) PublicKeyReader.get("d:/publicKeyFile");
		RSAPrivateKey privKey = (RSAPrivateKey) PrivateKeyReader.get("d:/privateKeyFile");
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);
		byte[] cipherText = cipher.doFinal(input.getBytes());
		//加密后的东西
		System.out.println("cipher: " + new String(cipherText));		
		//开始解密
		cipher.init(Cipher.DECRYPT_MODE, privKey); 
		byte[] plainText = cipher.doFinal(cipherText);
		System.out.println("plain : " + new String(plainText));
	}

}



查看结果:
cipher: J���
�nE��J�b9��CO��I�?�g[B{�w��u0����}�r6
�Q��Xa��ٝ�͊��N}n�]�@��_9!D��_�|k�ͪ&g�^��ɿ�XTa$�7��*�{7�R���v�S
plain : thisIsMyPassword$7788



说明加密解密成功。

备注,这里记录的只是测试方法,当然在实际使用过程中,可能还需要 对加密后的 byte[] 采用 base64 编码,转换成字符串存储起来,在解密的时候,先通过 base64 还原成 byte, 然后在解密,这样会更好。详细的方法,可以参考这篇文章 :http://www.yihaomen.com/article/java/376.htm

上一篇: spring datasource 密码加密后运行时解密的解决办法
下一篇: JAVA 获取在线用户数的方法

Avatar

xiaozhou 评论于: 2016-06-23

亲试,可以

Avatar

心然 评论于: 2015-12-16

服务器给我返回了一串376字节(string.length()=376)长度的公钥,我要怎么把他转换成PublicKey对象。 用上面的PublicKeyReader 里的get方法提示InvalidKeySpecException非法公钥,是要填充公钥长度再转换吗?该怎么做,求解。
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号