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

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


除非申明,文章均为一号门原创,转载请注明本文地址,谢谢!
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: java rsa
相关日志:
评论: 2 | 引用: 0 | 查看次数: -
回复回复xiaozhou[2016-06-23 10:28 AM | del]
亲试,可以
回复回复心然[2015-12-16 11:39 AM | del]
服务器给我返回了一串376字节(string.length()=376)长度的公钥,我要怎么把他转换成PublicKey对象。 用上面的PublicKeyReader 里的get方法提示InvalidKeySpecException非法公钥,是要填充公钥长度再转换吗?该怎么做,求解。
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.