Search in sources :

Example 31 with AlgorithmIdentifier

use of org.openecard.bouncycastle.asn1.x509.AlgorithmIdentifier in project BiglyBT by BiglySoftware.

the class JCEECPrivateKey method getEncoded.

/**
 * Return a PKCS8 representation of the key. The sequence returned
 * represents a full PrivateKeyInfo object.
 *
 * @return a PKCS8 representation of the key.
 */
@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);
    }
    PrivateKeyInfo info = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params.getDERObject()), new ECPrivateKeyStructure(this.getD()).getDERObject());
    try {
        dOut.writeObject(info);
        dOut.close();
    } catch (IOException e) {
        throw new RuntimeException("Error encoding EC private key");
    }
    return bOut.toByteArray();
}
Also used : X962Parameters(org.gudy.bouncycastle.asn1.x9.X962Parameters) X9ECParameters(org.gudy.bouncycastle.asn1.x9.X9ECParameters) ECNamedCurveParameterSpec(org.gudy.bouncycastle.jce.spec.ECNamedCurveParameterSpec) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ECPrivateKeyStructure(org.gudy.bouncycastle.asn1.sec.ECPrivateKeyStructure) IOException(java.io.IOException) PrivateKeyInfo(org.gudy.bouncycastle.asn1.pkcs.PrivateKeyInfo) AlgorithmIdentifier(org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 32 with AlgorithmIdentifier

use of org.openecard.bouncycastle.asn1.x509.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 33 with AlgorithmIdentifier

use of org.openecard.bouncycastle.asn1.x509.AlgorithmIdentifier in project BiglyBT by BiglySoftware.

the class PKCS7SignedData method getEncoded.

/**
 * return the bytes for the PKCS7SignedData object.
 */
public byte[] getEncoded() {
    try {
        digest = sig.sign();
        // Create the set of Hash algorithms. I've assumed this is the
        // set of all hash agorithms used to created the digest in the
        // "signerInfo" structure. I may be wrong.
        // 
        ASN1EncodableVector v = new ASN1EncodableVector();
        for (Iterator i = digestalgos.iterator(); i.hasNext(); ) {
            AlgorithmIdentifier a = new AlgorithmIdentifier(new DERObjectIdentifier((String) i.next()), null);
            v.add(a);
        }
        DERSet algos = new DERSet(v);
        // Create the contentInfo. Empty, I didn't implement this bit
        // 
        DERSequence contentinfo = new DERSequence(new DERObjectIdentifier(ID_PKCS7_DATA));
        // Get all the certificates
        // 
        v = new ASN1EncodableVector();
        for (Iterator i = certs.iterator(); i.hasNext(); ) {
            DERInputStream tempstream = new DERInputStream(new ByteArrayInputStream(((X509Certificate) i.next()).getEncoded()));
            v.add(tempstream.readObject());
        }
        DERSet dercertificates = new DERSet(v);
        // Create signerinfo structure.
        // 
        ASN1EncodableVector signerinfo = new ASN1EncodableVector();
        // Add the signerInfo version
        // 
        signerinfo.add(new DERInteger(signerversion));
        IssuerAndSerialNumber isAnds = new IssuerAndSerialNumber(new X509Name((ASN1Sequence) getIssuer(signCert.getTBSCertificate())), new DERInteger(signCert.getSerialNumber()));
        signerinfo.add(isAnds);
        // Add the digestAlgorithm
        // 
        signerinfo.add(new AlgorithmIdentifier(new DERObjectIdentifier(digestAlgorithm), new DERNull()));
        // 
        // Add the digestEncryptionAlgorithm
        // 
        signerinfo.add(new AlgorithmIdentifier(new DERObjectIdentifier(digestEncryptionAlgorithm), new DERNull()));
        // 
        // Add the digest
        // 
        signerinfo.add(new DEROctetString(digest));
        // 
        // Finally build the body out of all the components above
        // 
        ASN1EncodableVector body = new ASN1EncodableVector();
        body.add(new DERInteger(version));
        body.add(algos);
        body.add(contentinfo);
        body.add(new DERTaggedObject(false, 0, dercertificates));
        if (crls.size() > 0) {
            v = new ASN1EncodableVector();
            for (Iterator i = crls.iterator(); i.hasNext(); ) {
                DERInputStream t = new DERInputStream(new ByteArrayInputStream((((X509CRL) i.next()).getEncoded())));
                v.add(t.readObject());
            }
            DERSet dercrls = new DERSet(v);
            body.add(new DERTaggedObject(false, 1, dercrls));
        }
        // Only allow one signerInfo
        // 
        body.add(new DERSet(new DERSequence(signerinfo)));
        // Now we have the body, wrap it in it's PKCS7Signed shell
        // and return it
        // 
        ASN1EncodableVector whole = new ASN1EncodableVector();
        whole.add(new DERObjectIdentifier(ID_PKCS7_SIGNED_DATA));
        whole.add(new DERTaggedObject(0, new DERSequence(body)));
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dout = new DEROutputStream(bOut);
        dout.writeObject(new DERSequence(whole));
        dout.close();
        return bOut.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException(e.toString());
    }
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) AlgorithmIdentifier(org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier) X509Name(org.gudy.bouncycastle.asn1.x509.X509Name) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 34 with AlgorithmIdentifier

use of org.openecard.bouncycastle.asn1.x509.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 is
 *            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(InputStream is) throws CryptoException, IOException {
    byte[] streamContents = ReadUtil.readFully(is);
    EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));
    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(new ByteArrayInputStream(streamContents));
    if (pemInfo != null) {
        // It is - get DER from PEM
        streamContents = pemInfo.getContent();
    }
    try {
        // Read OpenSSL DER structure
        ASN1InputStream asn1InputStream = new ASN1InputStream(streamContents);
        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.getParameters());
                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) ByteArrayInputStream(java.io.ByteArrayInputStream) 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 35 with AlgorithmIdentifier

use of org.openecard.bouncycastle.asn1.x509.AlgorithmIdentifier in project xipki by xipki.

the class P12KeyGenerator method genECKeypair.

// CHECKSTYLE:SKIP
private KeyPairWithSubjectPublicKeyInfo genECKeypair(String curveNameOrOid, SecureRandom random) throws Exception {
    ASN1ObjectIdentifier curveOid = AlgorithmUtil.getCurveOidForCurveNameOrOid(curveNameOrOid);
    if (curveOid == null) {
        throw new IllegalArgumentException("invalid curveNameOrOid '" + curveNameOrOid + "'");
    }
    KeyPair kp = KeyUtil.generateECKeypair(curveOid, random);
    AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, curveOid);
    BCECPublicKey pub = (BCECPublicKey) kp.getPublic();
    byte[] keyData = pub.getQ().getEncoded(false);
    SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(algId, keyData);
    return new KeyPairWithSubjectPublicKeyInfo(kp, subjectPublicKeyInfo);
}
Also used : KeyPair(java.security.KeyPair) BCECPublicKey(org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Aggregations

AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)111 IOException (java.io.IOException)47 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)35 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)35 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)32 BigInteger (java.math.BigInteger)29 X509Certificate (java.security.cert.X509Certificate)27 X500Name (org.bouncycastle.asn1.x500.X500Name)27 DEROctetString (org.bouncycastle.asn1.DEROctetString)21 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)20 KeyPair (java.security.KeyPair)19 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)19 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)19 Date (java.util.Date)18 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)18 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)17 DERSequence (org.bouncycastle.asn1.DERSequence)16 KeyPairGenerator (java.security.KeyPairGenerator)15 PublicKey (java.security.PublicKey)14 InvalidKeyException (java.security.InvalidKeyException)13