- 使用私有CA签发用户证书
step[1]私钥还不能直接被使用,需要进行PKCS#8编码step[5]:openssl pkcs8 -topk8 -in rsa_private_key.key -out pkcs8_rsa_private_key.key -nocrypt
import cn.lettin.bean.response.QueryLettinTerritoryListResponseVo;
import cn.lettin.exception.GlobalException;
import cn.lettin.mapper.LettinTerritoryMapper;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static cn.lettin.exception.GlobalException.CREATE_CERT_ERROR;
@Slf4j
public class CertificateUtil {
public static String updateUserCertificate(String certBasePath, int userId, LettinTerritoryMapper lettinTerritoryMapper) throws GlobalException {
Map<String, String> userGwAuth = new HashMap<>();
List<QueryLettinTerritoryListResponseVo.TerritoryInfo> territoryInfos = lettinTerritoryMapper.queryLettinUserTerritoryByUserId(userId);
for (QueryLettinTerritoryListResponseVo.TerritoryInfo territoryInfo : territoryInfos) {
if (territoryInfo.getStatus()) {
List<String> gwIdList = lettinTerritoryMapper.queryLettinTerritoryGatewayByTerritoryId(territoryInfo.getTerritoryId());
for (String gatewayId : gwIdList) {
userGwAuth.put(gatewayId, String.valueOf(territoryInfo.getRoleId()));
}
}
}
return createCertificate(certBasePath, userId, userGwAuth, 36500);
}
public static String createCertificate(String certBasePath, int userId, Map<String, String> userGwAuth, int days) throws GlobalException {
String crtName = userId + "_certificate";
String pass = UniqIdUtils.getInstance().getUniqIDHashString();
String cACrtPath = certBasePath + "CA/ca";
String userPath = certBasePath + userId + "/";
String clientCrtPath = userPath + crtName;
String opensslPath = certBasePath + "openssl.cnf";
JSONObject ou = new JSONObject();
ou.put("userId", userId);
ou.put("timestamp", System.currentTimeMillis());
ou.put("userGwAuth", userGwAuth);
System.out.println(ou.toJSONString());
System.out.println(ou.toJSONString().length());
String[] step = new String[6];
step[0] = "mkdir -p " + userPath;
step[1] = "openssl genrsa -aes256 -passout pass:" + pass + " -out " + clientCrtPath + ".key 2048";
step[2] = "openssl rsa -in " + clientCrtPath + ".key -passin pass:" + pass + " -out " + clientCrtPath + ".key";
step[3] = "openssl req -new -key " + clientCrtPath + ".key -out " + clientCrtPath + ".csr -config " + opensslPath + " -subj /C=AU/ST=Some-State/O=Lettin/CN=dev/OU=Accle";
step[4] = "yes yes|openssl ca -in " + clientCrtPath + ".csr -out " + clientCrtPath + ".crt -cert " + cACrtPath + ".crt -keyfile " + cACrtPath + ".key -config " + opensslPath + " -days " + days;
step[5] = "openssl pkcs8 -topk8 -in " + clientCrtPath + ".key -out " + clientCrtPath + "_rsa.key -nocrypt";
String[] cmd = {"sh", "-c", ""};
Process ps = null;
try {
for (int i = 0; i < step.length; i++) {
if (i == 0) {
File file = new File(userPath);
if (file.exists()) {
continue;
}
}
cmd[2] = step[i];
log.info("执行命令: {}", cmd[2]);
ps = Runtime.getRuntime().exec(cmd);
int waitFor = ps.waitFor();
ps.destroy();
ps = null;
if (waitFor != 0) {
throw new GlobalException(CREATE_CERT_ERROR);
}
}
return clientCrtPath + ".crt";
} catch (Exception e) {
log.error("证书创建失败: {}", cmd[2]);
throw new GlobalException(CREATE_CERT_ERROR.setMessage(e.getMessage()));
} finally {
if (ps != null) {
ps.destroy();
}
}
}
}
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSAUtils {
public static KeyPair creatmyKey() throws Exception {
long mySeed = System.currentTimeMillis();
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
random.setSeed(mySeed);
keyGen.initialize(1024, random);
KeyPair myPair = keyGen.generateKeyPair();
return myPair;
}
public static byte[] encryptByPrivKey(byte[] privKeyInByte, byte[] data) throws Exception {
PKCS8EncodedKeySpec priv_spec = new PKCS8EncodedKeySpec(privKeyInByte);
KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
PrivateKey privKey = mykeyFactory.generatePrivate(priv_spec);
Cipher cipher = Cipher.getInstance(mykeyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privKey);
return cipher.doFinal(data);
}
public static byte[] encryptByPubKey(byte[] pubKeyInByte, byte[] data) throws Exception {
KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(pubKeyInByte);
PublicKey pubKey = mykeyFactory.generatePublic(pub_spec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
return cipher.doFinal(data);
}
public static byte[] decryptByPubKey(byte[] pubKeyInByte, byte[] data) throws Exception {
KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(pubKeyInByte);
PublicKey pubKey = mykeyFactory.generatePublic(pub_spec);
Cipher cipher = Cipher.getInstance(mykeyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, pubKey);
return cipher.doFinal(data);
}
public static byte[] decryptByPrivKey(byte[] privKeyInByte, byte[] data) throws Exception {
PKCS8EncodedKeySpec priv_spec = new PKCS8EncodedKeySpec(privKeyInByte);
KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
PrivateKey privKey = mykeyFactory.generatePrivate(priv_spec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privKey);
return cipher.doFinal(data);
}
public static boolean verify(byte[] pubKeyInByte, byte[] source, byte[] sign) throws Exception {
KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
Signature sig = Signature.getInstance("SHA1withRSA");
X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(pubKeyInByte);
PublicKey pubKey = mykeyFactory.generatePublic(pub_spec);
sig.initVerify(pubKey);
sig.update(source);
return sig.verify(sign);
}
public static byte[] sign(byte[] privKeyInByte, byte[] source) throws Exception {
PKCS8EncodedKeySpec priv_spec = new PKCS8EncodedKeySpec(privKeyInByte);
KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
PrivateKey privKey = mykeyFactory.generatePrivate(priv_spec);
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initSign(privKey);
sig.update(source);
return sig.sign();
}
}