Search in sources :

Example 1 with WeGooCryptoException

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);
    }
}
Also used : ECDomainParameters(com.github.zhenwei.core.crypto.params.ECDomainParameters) BCRSAPrivateKey(com.github.zhenwei.provider.jcajce.provider.asymmetric.rsa.BCRSAPrivateKey) X500Name(com.github.zhenwei.core.asn1.x500.X500Name) RSAKeyParameters(com.github.zhenwei.core.crypto.params.RSAKeyParameters) BcRSAContentSignerBuilder(com.github.zhenwei.pkix.operator.bc.BcRSAContentSignerBuilder) Random(java.util.Random) BcContentSignerBuilder(com.github.zhenwei.pkix.operator.bc.BcContentSignerBuilder) Date(java.util.Date) WeGooCryptoException(com.github.zhenwei.core.exception.WeGooCryptoException) BCECPrivateKey(com.github.zhenwei.provider.jcajce.provider.asymmetric.ec.BCECPrivateKey) ECPrivateKeyParameters(com.github.zhenwei.core.crypto.params.ECPrivateKeyParameters) WeGooCryptoException(com.github.zhenwei.core.exception.WeGooCryptoException) AsymmetricKeyParameter(com.github.zhenwei.core.crypto.params.AsymmetricKeyParameter) X509v3CertificateBuilder(com.github.zhenwei.pkix.cert.X509v3CertificateBuilder) ECParameterSpec(com.github.zhenwei.provider.jce.spec.ECParameterSpec) X509CertificateHolder(com.github.zhenwei.pkix.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) BcX509ExtensionUtils(com.github.zhenwei.pkix.cert.bc.BcX509ExtensionUtils) BcECContentSignerBuilder(com.github.zhenwei.pkix.operator.bc.BcECContentSignerBuilder)

Example 2 with WeGooCryptoException

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);
    }
}
Also used : WeGooKeyException(com.github.zhenwei.core.exception.WeGooKeyException) WeGooCryptoException(com.github.zhenwei.core.exception.WeGooCryptoException) KeyPairAlgEnum(com.github.zhenwei.core.enums.KeyPairAlgEnum) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) WeGooProvider(com.github.zhenwei.provider.jce.provider.WeGooProvider) PrivateKeyInfo(com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo) WeGooCryptoException(com.github.zhenwei.core.exception.WeGooCryptoException) WeGooKeyException(com.github.zhenwei.core.exception.WeGooKeyException) BaseWeGooException(com.github.zhenwei.core.exception.BaseWeGooException)

Example 3 with WeGooCryptoException

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);
    }
}
Also used : WeGooKeyException(com.github.zhenwei.core.exception.WeGooKeyException) DLSequence(com.github.zhenwei.core.asn1.DLSequence) KeyPairAlgEnum(com.github.zhenwei.core.enums.KeyPairAlgEnum) PrivateKeyInfo(com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString) WeGooCryptoException(com.github.zhenwei.core.exception.WeGooCryptoException) WeGooKeyException(com.github.zhenwei.core.exception.WeGooKeyException) BaseWeGooException(com.github.zhenwei.core.exception.BaseWeGooException)

Example 4 with WeGooCryptoException

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);
    }
}
Also used : X509CRL(java.security.cert.X509CRL) WeGooCryptoException(com.github.zhenwei.core.exception.WeGooCryptoException) WeGooCipherException(com.github.zhenwei.core.exception.WeGooCipherException) WeGooCryptoException(com.github.zhenwei.core.exception.WeGooCryptoException) IOException(java.io.IOException) BaseWeGooException(com.github.zhenwei.core.exception.BaseWeGooException)

Example 5 with WeGooCryptoException

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);
    }
}
Also used : X509CRLEntry(java.security.cert.X509CRLEntry) WeGooCryptoException(com.github.zhenwei.core.exception.WeGooCryptoException) BigInteger(java.math.BigInteger) CRLReason(java.security.cert.CRLReason) WeGooCryptoException(com.github.zhenwei.core.exception.WeGooCryptoException)

Aggregations

WeGooCryptoException (com.github.zhenwei.core.exception.WeGooCryptoException)11 BaseWeGooException (com.github.zhenwei.core.exception.BaseWeGooException)4 WeGooProvider (com.github.zhenwei.provider.jce.provider.WeGooProvider)4 WeGooKeyException (com.github.zhenwei.core.exception.WeGooKeyException)3 PrivateKeyInfo (com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo)2 KeyPairAlgEnum (com.github.zhenwei.core.enums.KeyPairAlgEnum)2 BigInteger (java.math.BigInteger)2 KeyStore (java.security.KeyStore)2 ASN1Encodable (com.github.zhenwei.core.asn1.ASN1Encodable)1 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)1 ASN1Set (com.github.zhenwei.core.asn1.ASN1Set)1 DEROctetString (com.github.zhenwei.core.asn1.DEROctetString)1 DLSequence (com.github.zhenwei.core.asn1.DLSequence)1 ContentInfo (com.github.zhenwei.core.asn1.pkcs.ContentInfo)1 SignedData (com.github.zhenwei.core.asn1.pkcs.SignedData)1 X500Name (com.github.zhenwei.core.asn1.x500.X500Name)1 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)1 DigestInfo (com.github.zhenwei.core.asn1.x509.DigestInfo)1 SubjectPublicKeyInfo (com.github.zhenwei.core.asn1.x509.SubjectPublicKeyInfo)1 AsymmetricKeyParameter (com.github.zhenwei.core.crypto.params.AsymmetricKeyParameter)1