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

RSA算法原理http://www.ruanyifeng.com/blog/2013/06/rsa_algorithm_part_one.html

"非对称加密算法"。

(1)乙方生成两把密钥(公钥和私钥)。公钥是公开的,任何人都可以获得,私钥则是保密的。

(2)甲方获取乙方的公钥,然后用它对信息加密。

(3)乙方得到加密后的信息,用私钥解密。

如果公钥加密的信息只有私钥解得开,那么只要私钥不泄漏,通信就是安全的。公钥用于加密,私钥用于解密.

原文:http://my.oschina.net/u/2284972/blog/525301

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

相关推荐