package util;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import java.io.*;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* RSA使用X509EncodedKeySpec、PKCS8EncodedKeySpec生成公钥和私钥
* 加密数据大小不能超过127 bytes
* @Description:加签、验签、加密、解密、生成公钥、私钥
* @date:2018年2月24日
*/
public class RSAUtil
{
public static void main(String[] args) throws Exception
{
//生成公私钥文件
RSAUtil.getKeyPair("E:/");
String publicKey = RSAUtil.readKeyFromFile("E:/publicKey.keystore");
String privateKey = RSAUtil.readKeyFromFile("E:/privateKey.keystore");
System.out.println("publicKey:"+publicKey);
System.out.println("privateKey:"+privateKey);
System.out.println("---------------------------------------------");
String sign = RSAUtil.signByPrivateKey("测试加签", privateKey);
System.out.println("sign:"+sign);
System.out.println("验签:"+RSAUtil.verifySignByPublicKey("测试加签", publicKey, sign));
System.out.println("---------------------------------------------");
String cipherText = RSAUtil.encryptByPublicKey("测试加密明文数据", RSAUtil.readPublicKeyFromString(publicKey));
System.out.println("cipherText:"+cipherText);
String plainText = RSAUtil.decryptByPrivateKey(cipherText, RSAUtil.readPrivateKeyFromString(privateKey));
System.out.println("plainText:"+plainText);
}
/**
* 生成公私钥对
* @param filePath 生成文件路径
*/
@SuppressWarnings("static-access")
public static void getKeyPair(String filePath)
{
KeyPairGenerator keyPairGenerator = null;
try
{
keyPairGenerator = keyPairGenerator.getInstance("RSA");
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
keyPairGenerator.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
String publicKeyString = new BASE64Encoder().encode(publicKey.getEncoded());
String privateKeyString =new BASE64Encoder().encode(privateKey.getEncoded());
try
{
BufferedWriter publicbw = new BufferedWriter(new FileWriter(new File(filePath+"/publicKey.keystore")));
BufferedWriter privatebw = new BufferedWriter(new FileWriter(new File(filePath+"/privateKey.keystore")));
publicbw.write(publicKeyString);
privatebw.write(privateKeyString);
publicbw.flush();
publicbw.close();
privatebw.flush();
privatebw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* 从文件中读取公钥或私钥
* @param filePath 文件路径
* @return 公钥或私钥
*/
public static String readKeyFromFile(String filePath)
{
try
{
BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));
String readLine = null;
StringBuilder sb = new StringBuilder();
while((readLine = br.readLine()) != null)
{
sb.append(readLine);
}
br.close();
return sb.toString();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
/**
* 从字符串中加载公钥
* @return 公钥
*/
public static RSAPublicKey readPublicKeyFromString(String publicKeyStr)
{
try
{
byte[] bt = new BASE64Decoder().decodeBuffer(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(bt);
return (RSAPublicKey) keyFactory.generatePublic(x509EncodedKeySpec);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (InvalidKeySpecException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 从字符串中加载私钥
* @return 私钥
*/
public static RSAPrivateKey readPrivateKeyFromString(String privateKeyStr)
{
try
{
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(privateKeyStr));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(pkcs8EncodedKeySpec);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (InvalidKeySpecException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 私钥加签
* @param content 报文
* @param privateKey 私钥
* @return 签名值
*/
public static String signByPrivateKey(String content,String privateKey)
{
try
{
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(privateKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Signature signature = Signature.getInstance("SHA256withRSA");//MD5withRSA
signature.initSign(priKey);
signature.update(content.getBytes());
byte[] sign = signature.sign();
return new BASE64Encoder().encode(sign);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* 公钥验签
* @param content 报文
* @param publicKey 公钥
* @param sign 签名值
* @return 验签是否通过
*/
public static boolean verifySignByPublicKey(String content,String publicKey,String sign)
{
try
{
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(publicKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(x509EncodedKeySpec);
Signature signature = Signature.getInstance("SHA256withRSA");//MD5withRSA
signature.initVerify(pubKey);
signature.update(content.getBytes());
return signature.verify(new BASE64Decoder().decodeBuffer(sign));
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
/**
* 公钥加密
* @param plainText 明文
* @param publicKey 公钥
* @return 密文
* @throws Exception
*/
public static String encryptByPublicKey(String plainText,RSAPublicKey publicKey) throws Exception
{
if(publicKey == null)
{
throw new Exception("公钥为空!");
}
Cipher cipher = null;
try
{
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(plainText.getBytes());
return new BASE64Encoder().encode(output);
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* 私钥解密
* @param cipherText 密文
* @param privateKey 私钥
* @return 明文
* @throws Exception
*/
public static String decryptByPrivateKey(String cipherText,RSAPrivateKey privateKey) throws Exception
{
if(privateKey == null)
{
throw new Exception("私钥为空!");
}
Cipher cipher = null;
try
{
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] output = cipher.doFinal(new BASE64Decoder().decodeBuffer(cipherText));
return new String(output);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
TCPClient.java
package util;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
public class TCPClient
{
private static String url = "21.131.4.33";
private static int port = 10000;
private static String publicKey = RSAUtil.readKeyFromFile("E:/publicKey.keystore");
private static String privateKey = RSAUtil.readKeyFromFile("E:/privateKey.keystore");
public static void main(String[] args) throws Exception
{
Map map = new HashMap();
map.put("name", "张三");
map.put("age", "23");
map.put("address", "北京市");
map.put("message", "测试数据");
String data = JSONObject.toJSONString(map);
//加签
String sign = RSAUtil.signByPrivateKey(data, privateKey);
//加密
String cipherText = RSAUtil.encryptByPublicKey(data, RSAUtil.readPublicKeyFromString(publicKey));
TCPClient tcpClient = new TCPClient();
tcpClient.sendMessage(url, port, sign+","+cipherText);
}
public void sendMessage(String url,int port,String message) throws UnknownHostException, IOException
{
Socket socket = new Socket(url,port);
OutputStream outputStream = socket.getOutputStream();
outputStream.write(message.getBytes());
socket.close();
outputStream.close();
}
}
TCPServer.java
package util;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer
{
private static int port = 10000;
private static String publicKey = RSAUtil.readKeyFromFile("E:/publicKey.keystore");
private static String privateKey = RSAUtil.readKeyFromFile("E:/privateKey.keystore");
public static void main(String[] args) throws Exception
{
TCPServer tcpServer = new TCPServer();
String message = tcpServer.getMessage(port);
//message = sign+cipherText
//System.out.println("message:"+message);
String sign = message.split(",")[0];
String cipherText = message.split(",")[1];
String plainText = RSAUtil.decryptByPrivateKey(cipherText, RSAUtil.readPrivateKeyFromString(privateKey));
if(RSAUtil.verifySignByPublicKey(plainText, publicKey, sign))
{
System.out.println("验签成功!");
System.out.println(plainText);
}
else
{
System.out.println("验签失败!");
}
}
public String getMessage(int port) throws IOException
{
String message = "";
ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
byte[] bs = new byte[1024];
int len = inputStream.read(bs);
message = new String(bs, 0, len);
socket.close();
serverSocket.close();
return message;
}
}