https://blog.csdn.net/linuxandroidwince/article/details/81141815
要看原理的点这里
秘钥对生成,项目根目录生成一个文件。
也可直接取打印出来的私钥和公钥
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import sun.misc.BASE64Encoder;//jdk1.8报黄不影响使用
/**
* 指定加密算法为RSA
*/
private static final String ALGORITHM = "RSA";
/**
* 密钥长度,用来初始化
*/
private static final int KEYSIZE = 1024;
/**
* 指定公钥存放文件
*/
private static String PUBLIC_KEY_FILE = "PublicKey";
/**
* 指定私钥存放文件
*/
private static String PRIVATE_KEY_FILE = "PrivateKey";
public static void main(String[] args) throws Exception {
generateKeyPair();
}
/**
* 本系统生成密钥对
*
* @throws Exception
*/
private static void generateKeyPair() throws Exception {
/** RSA算法要求有一个可信任的随机数源 */
/** 为RSA算法创建一个KeyPairGenerator对象 */
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
/** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
keyPairGenerator.initialize(KEYSIZE);
/** 生成密匙对 */
KeyPair keyPair = keyPairGenerator.generateKeyPair();
/** 得到公钥 */
Key publicKey = keyPair.getPublic();
/** 得到私钥 */
Key privateKey = keyPair.getPrivate();
byte[] publicKeyBytes = publicKey.getEncoded();
byte[] privateKeyBytes = privateKey.getEncoded();
String publicKeyBase64 = new BASE64Encoder().encode(publicKeyBytes);
String privateKeyBase64 = new BASE64Encoder().encode(privateKeyBytes);
System.out.println("系统公钥长度:" + publicKeyBase64.length());
System.out.println("系统公钥:" + publicKeyBase64);
System.out.println("系统私钥长度:" + privateKeyBase64.length());
System.out.println("系统私钥:" + privateKeyBase64);
ObjectOutputStream oos1 = null;
ObjectOutputStream oos2 = null;
try {
/** 用对象流将生成的密钥写入文件 */
oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));
oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));
oos1.writeObject(publicKey);
oos2.writeObject(privateKey);
} catch (Exception e) {
throw e;
} finally {
/** 清空缓存,关闭文件输出流 */
oos1.close();
oos2.close();
}
}
数据长度过长会报错,这是需使用分段式加密
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.Key;
import javax.crypto.Cipher;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class RSAUtil {
/** 指定加密算法为RSA */
private static final String ALGORITHM = "RSA";
/** 指定公钥存放文件 */
private static String PUBLIC_KEY_FILE = "PublicKey";
/** 指定私钥存放文件 */
private static String PRIVATE_KEY_FILE = "PrivateKey";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/** *//**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
//正常加密
public static String encryptOne(String source) throws Exception {
/** 获得公钥 */
Key publicKey = getKey(PUBLIC_KEY_FILE);
/** 得到Cipher对象来实现对源数据的RSA加密 */
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] b = source.getBytes();
/** 执行加密操作 */
byte[] b1 = cipher.doFinal(b);
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(b1);
}
//正常解密
public static String decrypt(String cryptograph) throws Exception {
Key privateKey = getKey(PRIVATE_KEY_FILE);
/** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
BASE64Decoder decoder = new BASE64Decoder();
byte[] b1 = decoder.decodeBuffer(cryptograph);
/** 执行解密操作 */
byte[] b = cipher.doFinal(b1);
return new String(b);
}
//分段加密
public static byte[] encrypt(String source) throws Exception {
Key publicKey = getKey(PUBLIC_KEY_FILE);
/** 得到Cipher对象来实现对源数据的RSA加密 */
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] b = source.getBytes();
int inputLen = b.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0)
{
if ( inputLen - offSet > MAX_ENCRYPT_BLOCK)
{
cache = cipher.doFinal( b, offSet, MAX_ENCRYPT_BLOCK);
}
else
{
cache = cipher.doFinal( b, offSet, inputLen - offSet);
}
out.write( cache, 0, cache. length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
//分段解密
public static String decryptByPrivateKey( byte[] encryptedData) throws Exception {
Key privateKey = getKey(PRIVATE_KEY_FILE);
Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
cipher.init(2, privateKey);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return new String(decryptedData);
}
private static Key getKey(String fileName) throws Exception, IOException {
Key key;
ObjectInputStream ois = null;
try {
/** 将文件中的私钥对象读出 */
ois = new ObjectInputStream(new FileInputStream(fileName));
key = (Key) ois.readObject();
} catch (Exception e) {
throw e;
} finally {
ois.close();
}
return key;
}
}
问题一:spring boot项目需改下面配置
private static String PUBLIC_KEY_FILE = "PublicKey";
替换为:
private static String PUBLIC_KEY_FILE = "classpath:key/PublicKey.txt";
getKey(String fileName)方法内
ois = new ObjectInputStream(new FileInputStream(fileName));
替换为
ois = new ObjectInputStream(new FileInputStream(ResourceUtils.getFile(fileName)));
不替换本地跑是没问题的,但是打包放到tomcat里会找不到你的静态文件。
其他项目同理,只需替换静态文件路径即可。
问题二:返回值前段调用或者java httpclient调用 会存在解密错误
org.apache.commons.codec.binary.Base64 base= new org.apache.commons.codec.binary.Base64();
String encodeToString = base.encodeToString(分段加密的byte[]);
如果php调用不存在上述问题,php有自带的方法调用。
同理调用的客户端也需要转一下
org.apache.commons.codec.binary.Base64 base= new org.apache.commons.codec.binary.Base64();
byte[] cipherTextArray = base64.decode(接收到的String);