use of com.github.zhenwei.core.exception.WeGooCryptoException in project LinLong-Java by zhenwei1108.
the class CertBuilder method generateCertificate.
/**
* @param [dn, publicKey, privateKey]
* @return java.security.cert.Certificate
* @author zhangzhenwei
* @description 生成证书
* todo just support sm2
* @date 2022/3/15 9:09 下午
* @since: 1.0.0
*/
public static byte[] generateCertificate(String subjectDn, String issuerDn, PublicKey publicKey, PrivateKey privateKey, SignAlgEnum signAlgEnum, int time, TimeUnit timeUnit) throws WeGooCryptoException {
try {
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
// SubjectPublicKeyInfo publicKeyInfo = (SubjectPublicKeyInfo)publicKey;
X500Name subject = new X500Name(subjectDn);
X500Name issuer = new X500Name(issuerDn);
byte[] bytes = new byte[15];
Random random = new Random();
random.nextBytes(bytes);
byte[] bytes1 = ByteArrayUtil.mergeBytes("9".getBytes(StandardCharsets.UTF_8), bytes);
BigInteger sn = new BigInteger(bytes1);
Date notBefore = DateUtil.now();
int max = Math.max(1, (int) timeUnit.toDays(time));
Date notAfter = DateUtil.nowPlusDays(max);
BcX509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
// 密钥用途: 签名和不可抵赖
int usage = KeyUsage.digitalSignature | KeyUsage.nonRepudiation;
// 使用者标识符
SubjectKeyIdentifier subjectKeyIdentifier = x509ExtensionUtils.createSubjectKeyIdentifier(publicKeyInfo);
// 授权者标识符
AuthorityKeyIdentifier authorityKeyIdentifier = x509ExtensionUtils.createAuthorityKeyIdentifier(publicKeyInfo);
// 判断是否签发根证书
if (subject.toString().equals(subject.toString())) {
// 根证书 颁发者标识符
authorityKeyIdentifier = x509ExtensionUtils.createAuthorityKeyIdentifier(publicKeyInfo);
// 补充证书签名用途
usage = usage | KeyUsage.keyCertSign;
}
X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuer, sn, notBefore, notAfter, subject, publicKeyInfo);
// 增加扩展项
Extension keyUsage = new Extension(Extension.keyUsage, false, new KeyUsage(usage).getEncoded());
Extension subjectKeyId = new Extension(Extension.subjectKeyIdentifier, false, subjectKeyIdentifier.getEncoded());
Extension authorityKeyId = new Extension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier.getEncoded());
AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(signAlgEnum.getOid());
AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(signAlgEnum.getDigestAlgEnum().getOid());
builder.addExtension(keyUsage);
builder.addExtension(subjectKeyId);
builder.addExtension(authorityKeyId);
X509CertificateHolder holder;
BcContentSignerBuilder signerBuilder;
AsymmetricKeyParameter keyParameters;
if (publicKey.getAlgorithm().equals("EC")) {
signerBuilder = new BcECContentSignerBuilder(sigAlgId, digAlgId);
BCECPrivateKey key = (BCECPrivateKey) privateKey;
ECParameterSpec parameters = key.getParameters();
ECDomainParameters params = new ECDomainParameters(parameters.getCurve(), parameters.getG(), parameters.getN());
keyParameters = new ECPrivateKeyParameters(key.getD(), params);
holder = builder.build(signerBuilder.build(keyParameters));
} else {
BCRSAPrivateKey key = (BCRSAPrivateKey) privateKey;
signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
keyParameters = new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent());
holder = builder.build(signerBuilder.build(keyParameters));
}
return holder.toASN1Structure().getEncoded();
} catch (Exception e) {
throw new WeGooCryptoException(CryptoExceptionMassageEnum.generate_cert_err, e);
}
}
use of com.github.zhenwei.core.exception.WeGooCryptoException in project LinLong-Java by zhenwei1108.
the class KeyBuilder method convertPrivateKey.
/**
* @param [privateKey]
* @return java.security.PrivateKey
* @author zhangzhenwei
* @description 私钥转换 byte[] to {@link PrivateKey}
* @date 2022/2/11 22:34
* @since 1.0
*/
public PrivateKey convertPrivateKey(byte[] privateKey) throws Exception {
try {
PrivateKeyInfo info = PrivateKeyInfo.getInstance(privateKey);
if (info == null) {
throw new WeGooKeyException(IExceptionEnum.params_err);
}
KeyPairAlgEnum algEnum = KeyPairAlgEnum.match(info.getPrivateKeyAlgorithm().getAlgorithm());
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey);
KeyFactory factory = KeyFactory.getInstance(algEnum.getAlg(), new WeGooProvider());
return factory.generatePrivate(spec);
} catch (WeGooCryptoException e) {
throw e;
} catch (Exception e) {
throw new WeGooKeyException(KeyExceptionMessageEnum.structure_private_key_err, e);
}
}
use of com.github.zhenwei.core.exception.WeGooCryptoException in project LinLong-Java by zhenwei1108.
the class KeyBuilder method getRealPrivateKey.
/**
* @param [privateKey]
* @return byte[]
* @author zhangzhenwei
* @description 获取裸私钥
* @date 2022/2/11 23:06
* @since 1.0
*/
public byte[] getRealPrivateKey(byte[] privateKey) throws WeGooCryptoException {
try {
PrivateKeyInfo info = PrivateKeyInfo.getInstance(privateKey);
if (info == null) {
throw new WeGooKeyException(IExceptionEnum.params_err);
}
KeyPairAlgEnum algEnum = KeyPairAlgEnum.match(info.getPrivateKeyAlgorithm().getAlgorithm());
// SM2 算法
if (algEnum.getAlg().equals(KeyPairAlgEnum.SM2_256.getAlg())) {
DLSequence dlSequence = (DLSequence) DLSequence.fromByteArray(privateKey);
byte[] priKeys = ((DEROctetString) dlSequence.getObjectAt(2)).getOctets();
dlSequence = (DLSequence) DLSequence.fromByteArray(priKeys);
DEROctetString derPriKey = (DEROctetString) dlSequence.getObjectAt(1);
return derPriKey.getOctets();
} else {
return info.getPrivateKey().getOctets();
}
} catch (WeGooKeyException e) {
throw e;
} catch (Exception e) {
throw new WeGooKeyException(KeyExceptionMessageEnum.parse_private_key_err, e);
}
}
use of com.github.zhenwei.core.exception.WeGooCryptoException in project LinLong-Java by zhenwei1108.
the class P7Builder method genSignedData.
/**
* @param []
* @return com.github.zhenwei.core.asn1.DEROctetString
* @author zhangzhenwei
* @description SignedData ::= SEQUENCE {
* version Version,
* digestAlgorithms DigestAlgorithmIdentifiers, -- set of DigestAlgorithmIdentifier
* contentInfo ContentInfo,
* certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL, --set of ExtendedCertificateOrCertificate
* crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
* signerInfos SignerInfos
* }
* @date 2022/3/3 9:46 下午
* @since: 1.0.0
*/
private ASN1Encodable genSignedData(SignAlgEnum signAlgEnum, byte[] signature, Certificate[] certificates, X509CRL[] crls) throws WeGooCryptoException {
try {
Version version = new Version(1);
DERSet digestAlgorithms = new DERSet(signAlgEnum.getDigestAlgEnum().getOid());
ContentInfo contentInfo = ContentInfo.getInstance(signature);
DERSet setOfCerts = new DERSet(certificates);
ASN1EncodableVector crlVector = new ASN1EncodableVector();
for (X509CRL crl : crls) {
crlVector.add(new ASN1InputStream(crl.getEncoded()).readObject());
}
DERSet setOfCrls = new DERSet(crlVector);
/**
* SignerInfo ::= SEQUENCE {
* version Version,
* issuerAndSerialNumber IssuerAndSerialNumber,
* digestAlgorithm DigestAlgorithmIdentifier,
* authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,
* digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
* encryptedDigest EncryptedDigest,
* unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL }
*/
SignerInfo signerInfo = SignerInfo.getInstance(null);
ASN1EncodableVector signerInfosVector = new ASN1EncodableVector();
signerInfosVector.add(signerInfo);
DERSet setOfSignerInfo = new DERSet(signerInfosVector);
return new SignedData(version, digestAlgorithms, contentInfo, setOfCerts, setOfCrls, setOfSignerInfo);
} catch (Exception e) {
throw new WeGooCryptoException(CryptoExceptionMassageEnum.generate_signed_data_err, e);
}
}
use of com.github.zhenwei.core.exception.WeGooCryptoException in project LinLong-Java by zhenwei1108.
the class CrlBuilder method getRevokeReason.
/**
* @param [certSn]
* @return java.lang.String
* @author zhangzhenwei
* @description 根据证书序列号获取注销原因
* @date 2022/2/16 16:20
* @since 1.0.8
*/
public String getRevokeReason(String certSn) throws WeGooCryptoException {
try {
BigInteger bigInteger = new BigInteger(certSn, 16);
X509CRLEntry entry = crl.getRevokedCertificate(bigInteger);
CRLReason revocationReason = entry.getRevocationReason();
return revocationReason.name();
} catch (Exception e) {
throw new WeGooCryptoException(CryptoExceptionMassageEnum.parse_crl_err, e);
}
}
Aggregations