博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java 私钥加密解密的例子
阅读量:7093 次
发布时间:2019-06-28

本文共 6196 字,大约阅读时间需要 20 分钟。

hot3.png

package com.rsa.zpl;import java.io.FileOutputStream; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SecureRandom; import java.util.Date;/** * 生成公钥和私钥 * @author zpl * */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();    }}package com.rsa.zpl;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;/** * 获取私钥 * @author zpl * */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 {        System.out.println(PrivateKeyReader.get("d:/privateKeyFile"));    }}package com.rsa.zpl;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;/** * 获取私钥 * @author zpl * */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);    }    public static void main(String[] args) {    	try {			System.out.println(get("D:\\publicKeyFile"));		} catch (Exception e) {			// TODO Auto-generated catch block			e.printStackTrace();		}	}}package com.rsa.zpl;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import javax.crypto.Cipher;/** * 公钥加密,私钥解密 * @author zpl * */public class TestEncryptAndDecrypt {        public static void main(String[] args) throws Exception {    	//测试公钥加密,私钥解密        String input = "thisIsMyPassword$7788";        RSAPublicKey pubKey = (RSAPublicKey) PublicKeyReader.get("d:/publicKeyFile");                        Cipher cipher = Cipher.getInstance("RSA");                cipher.init(Cipher.ENCRYPT_MODE, pubKey);        byte[] cipherText = cipher.doFinal(input.getBytes());        //加密后的东西//        System.out.println("cipher: " + new String(cipherText));                Cipher cipher1 = Cipher.getInstance("RSA");          RSAPrivateKey privKey = (RSAPrivateKey) PrivateKeyReader.get("d:/privateKeyFile");        //开始解密        cipher1.init(Cipher.DECRYPT_MODE, privKey);         byte[] plainText = cipher1.doFinal(cipherText);        System.out.println("plain : " + new String(plainText));    }}package com.rsa.zpl;import java.io.InputStream;import java.security.KeyFactory;import java.security.PublicKey;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import java.security.spec.X509EncodedKeySpec;import javax.crypto.Cipher;import org.apache.commons.io.IOUtils;/** * 公钥解密,私钥加密 * @author zpl * */public class TestEncryptAndDecrypt {        public static void main(String[] args) throws Exception {    	//加密部分*****************************************************8        String input = "thisIsMyPassword$zpl";        //RSAPublicKey pubKey = (RSAPublicKey) PublicKeyReader.get("d:/publicKeyFile");// 这是公钥加密的        RSAPrivateKey privKey = (RSAPrivateKey) PrivateKeyReader.get("D:/privateKeyFile");// 这是私钥加密的        Cipher cipher = Cipher.getInstance("RSA");                cipher.init(Cipher.ENCRYPT_MODE, privKey);        byte[] cipherText = cipher.doFinal(input.getBytes());        //加密后的东西        System.out.println("******************以上是加密部分cipher: " + new String(cipherText));                        // 解密部分 *****************************************************        Cipher cipher1 = Cipher.getInstance("RSA");         RSAPublicKey pubKey = (RSAPublicKey)get(TestEncryptAndDecrypt.class.getResourceAsStream("publicKeyFile"));// 公钥解密//        RSAPublicKey pubKey = (RSAPublicKey) PublicKeyReader.get("d:/publicKeyFile");// 公钥解密       // RSAPrivateKey privKey = (RSAPrivateKey) PrivateKeyReader.get("d:/privateKeyFile");//私钥解密用这个        //开始解密        cipher1.init(Cipher.DECRYPT_MODE, pubKey);         byte[] plainText = cipher1.doFinal(cipherText);        System.out.println("plain : " + new String(plainText));    }        public static PublicKey get(InputStream inputStream) throws Exception { 	byte[] keyBytes = IOUtils.toByteArray(inputStream);      X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);      KeyFactory kf = KeyFactory.getInstance("RSA");       return kf.generatePublic(spec);  }}cipher: 硤購镊爮x迨茦A吾 C ?承 蒹?{
{"C闥牖S卭学???滏?配鶫?b 風rNT AZ? 埖\探7oQ|X瓌9螿0 暗沌3达鲓8鼢?邆?G繬 ?貶??plain : thisIsMyPassword$zpl生成这样,说明是正确的

转载于:https://my.oschina.net/zplswf/blog/187521

你可能感兴趣的文章
poj 1811 Prime Test 大数素数测试+大数因子分解
查看>>
mysql主从同步
查看>>
获取搜索引擎来源关键词php示例
查看>>
一重循环解决百鸡百钱问题
查看>>
BufferedReader的ready与readLine使用,以及Premature EOF异常
查看>>
集合:ListIterator
查看>>
个人一周计划表
查看>>
RHEL7 添加用户,含sudo权限
查看>>
Example: Getting WMI Data from the Local Computer
查看>>
z-index只能在position属性值为relative或absolute或fixed的元素上有效。
查看>>
使用SecureCRT在远程主机和本地之间传输文件
查看>>
Android AsyncTask完全解析,带你从源码的角度彻底理解
查看>>
简单的NHibernate学习笔记
查看>>
screen工具的安装与使用
查看>>
洛谷 P2404 自然数的拆分问题
查看>>
7998元/年:百度推出百科微站服务
查看>>
智能设备如何防丢减损?
查看>>
linux sysrq
查看>>
Incorrect NSStringEncoding value 0x0000 detected.
查看>>
(转)as3数组的深复制和浅复制
查看>>