Keys类是 生成私钥 公钥类
package com.yy.gpo.http.client.service;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
public class Keys {
public static final String KEY_ALGORITHM = "RSA";
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
private static final String PUBLIC_KEY_PATH = "/Users/fayer/Documents/public-key.txt";
private static final String PRIVATE_KEY_PATH = "/Users/fayer/Documents/private-key.txt";
/**
* 生成私钥 公钥(生成公钥私钥文件的方法)
*/
public static void geration() {
KeyPairGenerator keyPairGenerator;
try {
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(new Date().toString().getBytes());
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
FileOutputStream fos = new FileOutputStream(PUBLIC_KEY_PATH);
fos.write(publicKeyBytes);
fos.close();
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
fos = new FileOutputStream(PRIVATE_KEY_PATH);
fos.write(privateKeyBytes);
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取公钥
*
* @param filename
* @return
* @throws Exception
*/
public static PublicKey getPublicKey(String filename) throws Exception {
File f = new File(Keys.class.getResource(filename).getPath());
// FileInputStream fis = new FileInputStream(f);
InputStream fis =Keys.class.getResourceAsStream(filename);
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);
}
/**
* 获取私钥
*
* @param filename
* @return
* @throws Exception
*/
public static PrivateKey getPrivateKey(String filename) throws Exception {
File f = new File(Keys.class.getResource(filename).getPath());
// FileInputStream fis = new FileInputStream(f);
InputStream fis =Keys.class.getResourceAsStream(filename);
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) {
}
package com.yy.gpo.http.client.service;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;
import com.yy.gpo.common.utils.ZipUtil;
public class SecretUtil {
// private static final String PUBLIC_KEY_PATH = "/Users/fayer/Documents/public-key.txt";
public static final String PUBLIC_KEY_PATH = "/public-key.txt";
public static final String PRIVATE_KEY_PATH = "/private-key.txt";
public static void main(String[] args) {
String rtnString = "";
System.out.println("");
try {
Cipher cipher = Cipher.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) Keys.getPublicKey(PUBLIC_KEY_PATH);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String encrypted= encrypt(rtnString, pubKey);
System.out.println("加密后:"+encrypted);
// 加密时超过117字节就报错。为此采用分段加密的办法来加密
RSAPrivateKey priKey = (RSAPrivateKey) Keys.getPrivateKey(PRIVATE_KEY_PATH);
cipher.init(Cipher.DECRYPT_MODE, priKey);
rtnString = decrypt(encrypted, priKey);
System.out.println(rtnString);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(ZipUtil.zipBase64String(rtnString));
// HttpGpoDiscountBillReq temp = JaxbXMLParser.convertXml2Obj(HttpGpoDiscountBillReq.class, rtnString, "utf-8");
System.out.println("");
}
//公钥加密,并转换成十六进制字符串打印出来
public static String encrypt(String content, PublicKey publicKey) throws Exception{
Cipher cipher=Cipher.getInstance("RSA");//java默认"RSA"="RSA/ECB/PKCS1Padding"
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int splitLength=((RSAPublicKey)publicKey).getModulus().bitLength()/8-11;
byte[][] arrays=splitBytes(content.getBytes(), splitLength);
StringBuffer sb=new StringBuffer();
for(byte[] array : arrays){
sb.append(bytesToHexString(cipher.doFinal(array)));
}
return sb.toString();
}
//私钥解密,并转换成十六进制字符串打印出来
public static String decrypt(String content, PrivateKey privateKey) throws Exception{
Cipher cipher=Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int splitLength=((RSAPrivateKey)privateKey).getModulus().bitLength()/8;
byte[] contentBytes=hexString2Bytes(content);
byte[][] arrays=splitBytes(contentBytes, splitLength);
StringBuffer sb=new StringBuffer();
for(byte[] array : arrays){
sb.append(new String(cipher.doFinal(array)));
}
return sb.toString();
}
//拆分byte数组
public static byte[][] splitBytes(byte[] bytes, int splitLength){
int x; //商,数据拆分的组数,余数不为0时+1
int y; //余数
y=bytes.length%splitLength;
if(y!=0){
x=bytes.length/splitLength+1;
}else{
x=bytes.length/splitLength;
}
byte[][] arrays=new byte[x][];
byte[] array;
for(int i=0; i<x; i++){
if(i==x-1 && bytes.length%splitLength!=0){
array=new byte[bytes.length%splitLength];
System.arraycopy(bytes, i*splitLength, array, 0, bytes.length%splitLength);
}else{
array=new byte[splitLength];
System.arraycopy(bytes, i*splitLength, array, 0, splitLength);
}
arrays[i]=array;
}
return arrays;
}
//byte数组转十六进制字符串
public static String bytesToHexString(byte[] bytes) {
StringBuffer sb = new StringBuffer(bytes.length);
String sTemp;
for (int i = 0; i < bytes.length; i++) {
sTemp = Integer.toHexString(0xFF & bytes[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
//十六进制字符串转byte数组
public static byte[] hexString2Bytes(String hex) {
int len = (hex.length() / 2);
hex=hex.toUpperCase();
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static byte toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}
}
具体的加密解密代码
//加密
Cipher cipher = Cipher.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) Keys.getPublicKey(SecretUtil.PUBLIC_KEY_PATH);
cipher.init(Cipher.DECRYPT_MODE, pubKey);
String reqXmlSecret=SecretUtil.encrypt(reqXml, pubKey);
//解密
RSAPrivateKey priKey = (RSAPrivateKey) Keys.getPrivateKey(SecretUtil.PRIVATE_KEY_PATH);
cipher.init(Cipher.DECRYPT_MODE, priKey);
rtnString = SecretUtil.decrypt(result,priKey);
}
本文介绍了一个使用Java实现的RSA加密解密过程,包括生成公钥和私钥、使用公钥进行加密及利用私钥解密的具体代码实现。此外,还提供了一种处理大块数据的分段加密解密方案。
1926

被折叠的 条评论
为什么被折叠?



