com.gitee.apanlh.util.algorithm.encrypt.asymmetric.AsymmetricKey Maven / Gradle / Ivy
package com.gitee.apanlh.util.algorithm.encrypt.asymmetric;
import com.gitee.apanlh.util.algorithm.KeyUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.gitee.apanlh.util.valid.ValidParam;
import java.io.Serializable;
/**
* 非对称加密密钥对对象
*
用于存放非对称加密算法(如SM2、RSA等)的公钥和私钥
*
支持十六进制和Base64编码格式
*
如果需要解码Key方法请使用{@link #decode()}
*
* @author Pan
*/
public class AsymmetricKey implements Serializable {
private static final long serialVersionUID = 1L;
/** 公钥 */
private byte[] publicKey;
/** 私钥 */
private byte[] privateKey;
/** 字符串公钥 */
private String publicKeyStr;
/** 字符串私钥 */
private String privateKeyStr;
/**
* 默认构造函数
*
* @author Pan
*/
public AsymmetricKey() {
super();
}
/**
* 构造函数-初始化公钥/私钥
*
默认转化Base64
*
* @author Pan
* @param publicKey 公钥
* @param privateKey 私钥
*/
public AsymmetricKey(byte[] publicKey, byte[] privateKey) {
this(publicKey, privateKey, true);
}
/**
* 构造函数-初始化公钥/私钥
*
自定义转化格式
*
注意:Base64编码则默认RFC4648标准
*
* @author Pan
* @param publicKey 公钥
* @param privateKey 私钥
* @param isBase64 true:Base64 false:十六进制
*/
public AsymmetricKey(byte[] publicKey, byte[] privateKey, boolean isBase64) {
boolean b1 = ValidParam.isEmpty(publicKey);
boolean b2 = ValidParam.isEmpty(privateKey);
Assert.isFalse(b1 && b2);
this.publicKey = publicKey;
this.privateKey = privateKey;
if (!b1) {
this.publicKeyStr = KeyUtils.encode(publicKey, isBase64);
this.publicKey = null;
}
if (!b2) {
this.privateKeyStr = KeyUtils.encode(privateKey, isBase64);
this.privateKey = null;
}
}
/**
* 获取公钥
*
* @author Pan
* @return byte[]
*/
public byte[] getPublicKey() {
return publicKey;
}
/**
* 设置公钥值
*
* @author Pan
* @param publicKey 公钥
*/
public void setPublicKey(byte[] publicKey) {
this.publicKey = publicKey;
}
/**
* 获取私钥
*
* @author Pan
* @return byte[]
*/
public byte[] getPrivateKey() {
return privateKey;
}
/**
* 设置私钥值
*
* @author Pan
* @param privateKey 私钥
*/
public void setPrivateKey(byte[] privateKey) {
this.privateKey = privateKey;
}
/**
* 获取公钥
*
* @author Pan
* @return byte[]
*/
public String getPublicKeyStr() {
return publicKeyStr;
}
/**
* 设置公钥值
*
* @author Pan
* @param publicKeyStr 公钥
*/
public void setPublicKeyStr(String publicKeyStr) {
this.publicKeyStr = publicKeyStr;
}
/**
* 获取私钥
*
* @author Pan
* @return byte[]
*/
public String getPrivateKeyStr() {
return privateKeyStr;
}
/**
* 设置私钥值
*
* @author Pan
* @param privateKeyStr 私钥
*/
public void setPrivateKeyStr(String privateKeyStr) {
this.privateKeyStr = privateKeyStr;
}
/**
* 将公钥和私钥的字符串编码解码为字节数组
*
注意:编码格式只能是十六进制或Base64编码
*
* @author Pan
*/
public void decode() {
if (ValidParam.isEmpty(this.publicKeyStr)) {
setPublicKey(KeyUtils.decode(this.publicKeyStr));
}
if (ValidParam.isEmpty(this.privateKeyStr)) {
setPrivateKey(KeyUtils.decode(this.privateKeyStr));
}
}
}