Search in sources :

Example 76 with AlgorithmIdentifier

use of com.android.apksig.internal.pkcs7.AlgorithmIdentifier in project BiglyBT by BiglySoftware.

the class JCEECPublicKey method getEncoded.

@Override
public byte[] getEncoded() {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    X962Parameters params = null;
    if (ecSpec instanceof ECNamedCurveParameterSpec) {
        params = new X962Parameters(X962NamedCurves.getOID(((ECNamedCurveParameterSpec) ecSpec).getName()));
    } else {
        X9ECParameters ecP = new X9ECParameters(ecSpec.getCurve(), ecSpec.getG(), ecSpec.getN(), ecSpec.getH(), ecSpec.getSeed());
        params = new X962Parameters(ecP);
    }
    ASN1OctetString p = (ASN1OctetString) (new X9ECPoint(this.getQ()).getDERObject());
    SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params.getDERObject()), p.getOctets());
    try {
        dOut.writeObject(info);
        dOut.close();
    } catch (IOException e) {
        throw new RuntimeException("Error encoding EC public key");
    }
    return bOut.toByteArray();
}
Also used : ECNamedCurveParameterSpec(org.gudy.bouncycastle.jce.spec.ECNamedCurveParameterSpec) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) SubjectPublicKeyInfo(org.gudy.bouncycastle.asn1.x509.SubjectPublicKeyInfo) AlgorithmIdentifier(org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 77 with AlgorithmIdentifier

use of com.android.apksig.internal.pkcs7.AlgorithmIdentifier in project keycloak by keycloak.

the class CertificateUtils method createSigner.

/**
 * Creates the content signer for generation of Version 1 {@link java.security.cert.X509Certificate}.
 *
 * @param privateKey the private key
 *
 * @return the content signer
 */
public static ContentSigner createSigner(PrivateKey privateKey) {
    try {
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256WithRSAEncryption");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        return new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(PrivateKeyFactory.createKey(privateKey.getEncoded()));
    } catch (Exception e) {
        throw new RuntimeException("Could not create content signer.", e);
    }
}
Also used : BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder)

Example 78 with AlgorithmIdentifier

use of com.android.apksig.internal.pkcs7.AlgorithmIdentifier in project keycloak by keycloak.

the class CertificateUtils method generateV3Certificate.

/**
 * Generates version 3 {@link java.security.cert.X509Certificate}.
 *
 * @param keyPair the key pair
 * @param caPrivateKey the CA private key
 * @param caCert the CA certificate
 * @param subject the subject name
 *
 * @return the x509 certificate
 *
 * @throws Exception the exception
 */
public static X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPrivateKey, X509Certificate caCert, String subject) throws Exception {
    try {
        X500Name subjectDN = new X500Name("CN=" + subject);
        // Serial Number
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        BigInteger serialNumber = BigInteger.valueOf(Math.abs(random.nextInt()));
        // Validity
        Date notBefore = new Date(System.currentTimeMillis());
        Date notAfter = new Date(System.currentTimeMillis() + (((1000L * 60 * 60 * 24 * 30)) * 12) * 3);
        // SubjectPublicKeyInfo
        SubjectPublicKeyInfo subjPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()), serialNumber, notBefore, notAfter, subjectDN, subjPubKeyInfo);
        DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);
        // Subject Key Identifier
        certGen.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo));
        // Authority Key Identifier
        certGen.addExtension(Extension.authorityKeyIdentifier, false, x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo));
        // Key Usage
        certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
        // Extended Key Usage
        KeyPurposeId[] EKU = new KeyPurposeId[2];
        EKU[0] = KeyPurposeId.id_kp_emailProtection;
        EKU[1] = KeyPurposeId.id_kp_serverAuth;
        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));
        // Basic Constraints
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0));
        // Content Signer
        ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC").build(caPrivateKey);
        // Certificate
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
    } catch (Exception e) {
        throw new RuntimeException("Error creating X509v3Certificate.", e);
    }
}
Also used : BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) BigInteger(java.math.BigInteger) X509ExtensionUtils(org.bouncycastle.cert.X509ExtensionUtils) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 79 with AlgorithmIdentifier

use of com.android.apksig.internal.pkcs7.AlgorithmIdentifier in project keystore-explorer by kaikramer.

the class OpenSslPvkUtil method load.

/**
 * Load an unencrypted OpenSSL private key from the stream. The encoding of
 * the private key may be PEM or DER.
 *
 * @param pvkData Stream to load the unencrypted private key from
 * @return The private key
 * @throws PrivateKeyEncryptedException If private key is encrypted
 * @throws CryptoException              Problem encountered while loading the private key
 * @throws IOException                  An I/O error occurred
 */
public static PrivateKey load(byte[] pvkData) throws CryptoException, IOException {
    EncryptionType encType = getEncryptionType(pvkData);
    if (encType == null) {
        throw new CryptoException(res.getString("NotValidOpenSsl.exception.message"));
    }
    if (encType == ENCRYPTED) {
        throw new PrivateKeyEncryptedException(res.getString("OpenSslIsEncrypted.exception.message"));
    }
    // Check if stream is PEM encoded
    PemInfo pemInfo = PemUtil.decode(pvkData);
    if (pemInfo != null) {
        // It is - get DER from PEM
        pvkData = pemInfo.getContent();
    }
    try (ASN1InputStream asn1InputStream = new ASN1InputStream(pvkData)) {
        // Read OpenSSL DER structure
        ASN1Primitive openSsl = asn1InputStream.readObject();
        asn1InputStream.close();
        if (openSsl instanceof ASN1Sequence) {
            ASN1Sequence seq = (ASN1Sequence) openSsl;
            if (seq.size() == 9) {
                // RSA private key
                BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
                BigInteger modulus = ((ASN1Integer) seq.getObjectAt(1)).getValue();
                BigInteger publicExponent = ((ASN1Integer) seq.getObjectAt(2)).getValue();
                BigInteger privateExponent = ((ASN1Integer) seq.getObjectAt(3)).getValue();
                BigInteger primeP = ((ASN1Integer) seq.getObjectAt(4)).getValue();
                BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(5)).getValue();
                BigInteger primeExponentP = ((ASN1Integer) seq.getObjectAt(6)).getValue();
                BigInteger primeExponenetQ = ((ASN1Integer) seq.getObjectAt(7)).getValue();
                BigInteger crtCoefficient = ((ASN1Integer) seq.getObjectAt(8)).getValue();
                if (!version.equals(VERSION)) {
                    throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
                }
                RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponenetQ, crtCoefficient);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                return keyFactory.generatePrivate(rsaPrivateCrtKeySpec);
            } else if (seq.size() == 6) {
                // DSA private key
                BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
                BigInteger primeModulusP = ((ASN1Integer) seq.getObjectAt(1)).getValue();
                BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(2)).getValue();
                BigInteger generatorG = ((ASN1Integer) seq.getObjectAt(3)).getValue();
                // publicExponentY not req for pvk: sequence.getObjectAt(4);
                BigInteger secretExponentX = ((ASN1Integer) seq.getObjectAt(5)).getValue();
                if (!version.equals(VERSION)) {
                    throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
                }
                DSAPrivateKeySpec dsaPrivateKeySpec = new DSAPrivateKeySpec(secretExponentX, primeModulusP, primeQ, generatorG);
                KeyFactory keyFactory = KeyFactory.getInstance("DSA");
                return keyFactory.generatePrivate(dsaPrivateKeySpec);
            } else if (seq.size() >= 2) {
                // EC private key (RFC 5915)
                org.bouncycastle.asn1.sec.ECPrivateKey pKey = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(seq);
                AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParametersObject());
                PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey);
                return new JcaPEMKeyConverter().getPrivateKey(privInfo);
            } else {
                throw new CryptoException(MessageFormat.format(res.getString("OpenSslSequenceIncorrectSize.exception.message"), "" + seq.size()));
            }
        } else {
            throw new CryptoException(res.getString("OpenSslSequenceNotFound.exception.message"));
        }
    } catch (Exception ex) {
        throw new CryptoException(res.getString("NoLoadOpenSslPrivateKey.exception.message"), ex);
    }
}
Also used : RSAPrivateCrtKeySpec(java.security.spec.RSAPrivateCrtKeySpec) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) PemInfo(org.kse.utilities.pem.PemInfo) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) CryptoException(org.kse.crypto.CryptoException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DSAPrivateKeySpec(java.security.spec.DSAPrivateKeySpec) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) BigInteger(java.math.BigInteger) CryptoException(org.kse.crypto.CryptoException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) KeyFactory(java.security.KeyFactory) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 80 with AlgorithmIdentifier

use of com.android.apksig.internal.pkcs7.AlgorithmIdentifier in project keystore-explorer by kaikramer.

the class EccUtil method detectEdDSACurve.

/**
 * Detect which one of the two EdDSA curves (Ed25519 or Ed448) the given privateKey is.
 *
 * @param privateKey An EdDSA private key
 * @return Ed25519 or Ed448
 * @throws InvalidParameterException if privateKey is not a EdDSA key
 */
public static EdDSACurves detectEdDSACurve(PrivateKey privateKey) {
    PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(privateKey.getEncoded());
    AlgorithmIdentifier algorithm = privateKeyInfo.getPrivateKeyAlgorithm();
    ASN1ObjectIdentifier algOid = algorithm.getAlgorithm();
    return EdDSACurves.resolve(algOid);
}
Also used : PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Aggregations

AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)249 IOException (java.io.IOException)144 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)140 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)75 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)71 BigInteger (java.math.BigInteger)60 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)55 X500Name (org.bouncycastle.asn1.x500.X500Name)50 X509Certificate (java.security.cert.X509Certificate)44 Date (java.util.Date)43 ContentSigner (org.bouncycastle.operator.ContentSigner)39 DEROctetString (org.bouncycastle.asn1.DEROctetString)38 OutputStream (java.io.OutputStream)37 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)36 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)34 PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)33 BcRSAContentSignerBuilder (org.bouncycastle.operator.bc.BcRSAContentSignerBuilder)33 DefaultDigestAlgorithmIdentifierFinder (org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder)31 DefaultSignatureAlgorithmIdentifierFinder (org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder)31 DEROctetString (com.github.zhenwei.core.asn1.DEROctetString)28