这个是jdk的公钥和私钥的生成与使用
``` python
package cn.itcast.controller;
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.security.Key;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.PrivateKey;import java.security.PublicKey; import javax.crypto.Cipher; import org.junit.Test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping("/PublicPrivateKey")public class PublicPrivateKey { private static final String ALGOGRITHM = "RSA"; private static final String PUBLIC_KEY_PATH = "public.key"; private static final String PRIVATE_KEY_PATH = "private.key"; @Test public void testGenerate() throws Exception { //KeyPairGenerator引擎类用于产生密钥对,JDK(7)默认支持的算法有,DiffieHellman、DSA、RSA、EC KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGOGRITHM); //产生密钥对 KeyPair keyPair = generator.generateKeyPair(); //获取公钥 PublicKey publicKey = keyPair.getPublic(); //获取私钥 PrivateKey privateKey = keyPair.getPrivate(); //将公钥与私钥写入文件,以备后用 writeKey(PUBLIC_KEY_PATH, publicKey); writeKey(PRIVATE_KEY_PATH, privateKey); } @RequestMapping("/ecrypt.do") public void ecrypt() throws Exception { Cipher cipher = Cipher.getInstance(ALGOGRITHM); //读取私钥,进行加密 PrivateKey privateKey = (PrivateKey) readKey("E:\\Users\\Administrator\\workspace\\springmvc_mybatis\\private.key"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); //加密 String mingwen = "我的明文"; //加密后的字节数组 byte[] results = cipher.doFinal(mingwen.getBytes()); String recvInfo = new String(results); System.out.println(recvInfo); PublicKey publicKey = (PublicKey) readKey("E:\\Users\\Administrator\\workspace\\springmvc_mybatis\\public.key"); cipher.init(Cipher.DECRYPT_MODE, publicKey); //解密 byte[] deciphered = cipher.doFinal(results); //得到明文 String publicvalue = new String(deciphered); System.out.println(publicvalue); } public void writeKey(String path, Key key) throws Exception { FileOutputStream fos = new FileOutputStream(path); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(key); oos.close(); } public static Key readKey(String path) throws Exception { FileInputStream fis = new FileInputStream(path); ObjectInputStream bis = new ObjectInputStream(fis); Object object = bis.readObject(); bis.close(); return (Key) object;
```
```
```