Search in sources :

Example 36 with ASN1InputStream

use of org.gudy.bouncycastle.asn1.ASN1InputStream 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 37 with ASN1InputStream

use of org.gudy.bouncycastle.asn1.ASN1InputStream in project xades4j by luisgoncalves.

the class DefaultTimeStampVerificationProvider method verifyToken.

@Override
public Date verifyToken(byte[] timeStampToken, byte[] tsDigestInput) throws TimeStampTokenVerificationException {
    TimeStampToken tsToken;
    try {
        ASN1InputStream asn1is = new ASN1InputStream(timeStampToken);
        ContentInfo tsContentInfo = ContentInfo.getInstance(asn1is.readObject());
        asn1is.close();
        tsToken = new TimeStampToken(tsContentInfo);
    } catch (IOException ex) {
        throw new TimeStampTokenStructureException("Error parsing encoded token", ex);
    } catch (TSPException ex) {
        throw new TimeStampTokenStructureException("Invalid token", ex);
    }
    X509Certificate tsaCert = null;
    try {
        /* Validate the TSA certificate */
        LinkedList<X509Certificate> certs = new LinkedList<X509Certificate>();
        for (Object certHolder : tsToken.getCertificates().getMatches(new AllCertificatesSelector())) {
            certs.add(this.x509CertificateConverter.getCertificate((X509CertificateHolder) certHolder));
        }
        ValidationData vData = this.certificateValidationProvider.validate(x509CertSelectorConverter.getCertSelector(tsToken.getSID()), tsToken.getTimeStampInfo().getGenTime(), certs);
        tsaCert = vData.getCerts().get(0);
    } catch (CertificateException ex) {
        throw new TimeStampTokenVerificationException(ex.getMessage(), ex);
    } catch (XAdES4jException ex) {
        throw new TimeStampTokenTSACertException("cannot validate TSA certificate", ex);
    }
    try {
        tsToken.validate(this.signerInfoVerifierBuilder.build(tsaCert));
    } catch (TSPValidationException ex) {
        throw new TimeStampTokenSignatureException("Invalid token signature or certificate", ex);
    } catch (Exception ex) {
        throw new TimeStampTokenVerificationException("Error when verifying the token signature", ex);
    }
    org.bouncycastle.tsp.TimeStampTokenInfo tsTokenInfo = tsToken.getTimeStampInfo();
    try {
        String digestAlgUri = uriForDigest(tsTokenInfo.getMessageImprintAlgOID());
        MessageDigest md = messageDigestProvider.getEngine(digestAlgUri);
        if (!Arrays.equals(md.digest(tsDigestInput), tsTokenInfo.getMessageImprintDigest())) {
            throw new TimeStampTokenDigestException();
        }
    } catch (UnsupportedAlgorithmException ex) {
        throw new TimeStampTokenVerificationException("The token's digest algorithm is not supported", ex);
    }
    return tsTokenInfo.getGenTime();
}
Also used : CertificateException(java.security.cert.CertificateException) TimeStampTokenVerificationException(xades4j.providers.TimeStampTokenVerificationException) TimeStampTokenSignatureException(xades4j.providers.TimeStampTokenSignatureException) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) XAdES4jException(xades4j.XAdES4jException) TimeStampTokenDigestException(xades4j.providers.TimeStampTokenDigestException) MessageDigest(java.security.MessageDigest) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) TimeStampTokenStructureException(xades4j.providers.TimeStampTokenStructureException) TSPValidationException(org.bouncycastle.tsp.TSPValidationException) TimeStampTokenTSACertException(xades4j.providers.TimeStampTokenTSACertException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) LinkedList(java.util.LinkedList) TSPValidationException(org.bouncycastle.tsp.TSPValidationException) XAdES4jException(xades4j.XAdES4jException) TimeStampTokenTSACertException(xades4j.providers.TimeStampTokenTSACertException) TimeStampTokenStructureException(xades4j.providers.TimeStampTokenStructureException) TSPException(org.bouncycastle.tsp.TSPException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) TimeStampTokenDigestException(xades4j.providers.TimeStampTokenDigestException) TimeStampTokenVerificationException(xades4j.providers.TimeStampTokenVerificationException) TimeStampTokenSignatureException(xades4j.providers.TimeStampTokenSignatureException) ValidationData(xades4j.providers.ValidationData) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken)

Example 38 with ASN1InputStream

use of org.gudy.bouncycastle.asn1.ASN1InputStream in project nuls by nuls-io.

the class SM2Utils method verifySign.

public static boolean verifySign(byte[] userId, byte[] publicKey, byte[] sourceData, byte[] signData) throws IOException {
    if (publicKey == null || publicKey.length == 0) {
        return false;
    }
    if (sourceData == null || sourceData.length == 0) {
        return false;
    }
    SM2 sm2 = SM2.Instance();
    ECPoint userKey = sm2.ecc_curve.decodePoint(publicKey);
    SM3Digest sm3 = new SM3Digest();
    byte[] z = sm2.sm2GetZ(userId, userKey);
    sm3.update(z, 0, z.length);
    sm3.update(sourceData, 0, sourceData.length);
    byte[] md = new byte[32];
    sm3.doFinal(md, 0);
    ByteArrayInputStream bis = new ByteArrayInputStream(signData);
    ASN1InputStream dis = new ASN1InputStream(bis);
    DERObject derObj = dis.readObject();
    Enumeration<DERInteger> e = ((ASN1Sequence) derObj).getObjects();
    BigInteger r = ((DERInteger) e.nextElement()).getValue();
    BigInteger s = ((DERInteger) e.nextElement()).getValue();
    SM2Result sm2Result = new SM2Result();
    sm2Result.r = r;
    sm2Result.s = s;
    sm2.sm2Verify(md, userKey, sm2Result.r, sm2Result.s, sm2Result);
    return sm2Result.r.equals(sm2Result.R);
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) DERObject(org.bouncycastle.asn1.DERObject) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ByteArrayInputStream(java.io.ByteArrayInputStream) BigInteger(java.math.BigInteger) ECPoint(org.bouncycastle.math.ec.ECPoint) DERInteger(org.bouncycastle.asn1.DERInteger)

Example 39 with ASN1InputStream

use of org.gudy.bouncycastle.asn1.ASN1InputStream in project airavata by apache.

the class X509SecurityContext method generateShortLivedCredential.

public KeyAndCertCredential generateShortLivedCredential(String userDN, String caCertPath, String caKeyPath, String caPwd) throws Exception {
    // 15 minutes
    final long CredentialGoodFromOffset = 1000L * 60L * 15L;
    // ago
    final long startTime = System.currentTimeMillis() - CredentialGoodFromOffset;
    final long endTime = startTime + 30 * 3600 * 1000;
    String keyLengthProp = "1024";
    int keyLength = Integer.parseInt(keyLengthProp);
    String signatureAlgorithm = "SHA1withRSA";
    KeyAndCertCredential caCred = getCACredential(caCertPath, caKeyPath, caPwd);
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(caCred.getKey().getAlgorithm());
    kpg.initialize(keyLength);
    KeyPair pair = kpg.generateKeyPair();
    X500Principal subjectDN = new X500Principal(userDN);
    Random rand = new Random();
    SubjectPublicKeyInfo publicKeyInfo;
    try {
        publicKeyInfo = SubjectPublicKeyInfo.getInstance(new ASN1InputStream(pair.getPublic().getEncoded()).readObject());
    } catch (IOException e) {
        throw new InvalidKeyException("Can not parse the public key" + "being included in the short lived certificate", e);
    }
    X500Name issuerX500Name = CertificateHelpers.toX500Name(caCred.getCertificate().getSubjectX500Principal());
    X500Name subjectX500Name = CertificateHelpers.toX500Name(subjectDN);
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerX500Name, new BigInteger(20, rand), new Date(startTime), new Date(endTime), subjectX500Name, publicKeyInfo);
    AlgorithmIdentifier sigAlgId = X509v3CertificateBuilder.extractAlgorithmId(caCred.getCertificate());
    X509Certificate certificate = certBuilder.build(caCred.getKey(), sigAlgId, signatureAlgorithm, null, null);
    certificate.checkValidity(new Date());
    certificate.verify(caCred.getCertificate().getPublicKey());
    KeyAndCertCredential result = new KeyAndCertCredential(pair.getPrivate(), new X509Certificate[] { certificate, caCred.getCertificate() });
    return result;
}
Also used : KeyPair(java.security.KeyPair) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyPairGenerator(java.security.KeyPairGenerator) IOException(java.io.IOException) X500Name(org.bouncycastle.asn1.x500.X500Name) InvalidKeyException(java.security.InvalidKeyException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) Random(java.util.Random) X509v3CertificateBuilder(eu.emi.security.authn.x509.helpers.proxy.X509v3CertificateBuilder) KeyAndCertCredential(eu.emi.security.authn.x509.impl.KeyAndCertCredential) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger)

Example 40 with ASN1InputStream

use of org.gudy.bouncycastle.asn1.ASN1InputStream in project airavata by apache.

the class X509SecurityContext method generateShortLivedCredential.

public KeyAndCertCredential generateShortLivedCredential(String userDN, String caCertPath, String caKeyPath, String caPwd) throws Exception {
    // 15 minutes
    final long CredentialGoodFromOffset = 1000L * 60L * 15L;
    // ago
    final long startTime = System.currentTimeMillis() - CredentialGoodFromOffset;
    final long endTime = startTime + 30 * 3600 * 1000;
    String keyLengthProp = "1024";
    int keyLength = Integer.parseInt(keyLengthProp);
    String signatureAlgorithm = "SHA1withRSA";
    KeyAndCertCredential caCred = getCACredential(caCertPath, caKeyPath, caPwd);
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(caCred.getKey().getAlgorithm());
    kpg.initialize(keyLength);
    KeyPair pair = kpg.generateKeyPair();
    X500Principal subjectDN = new X500Principal(userDN);
    Random rand = new Random();
    SubjectPublicKeyInfo publicKeyInfo;
    try {
        publicKeyInfo = SubjectPublicKeyInfo.getInstance(new ASN1InputStream(pair.getPublic().getEncoded()).readObject());
    } catch (IOException e) {
        throw new InvalidKeyException("Can not parse the public key" + "being included in the short lived certificate", e);
    }
    X500Name issuerX500Name = CertificateHelpers.toX500Name(caCred.getCertificate().getSubjectX500Principal());
    X500Name subjectX500Name = CertificateHelpers.toX500Name(subjectDN);
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerX500Name, new BigInteger(20, rand), new Date(startTime), new Date(endTime), subjectX500Name, publicKeyInfo);
    AlgorithmIdentifier sigAlgId = X509v3CertificateBuilder.extractAlgorithmId(caCred.getCertificate());
    X509Certificate certificate = certBuilder.build(caCred.getKey(), sigAlgId, signatureAlgorithm, null, null);
    certificate.checkValidity(new Date());
    certificate.verify(caCred.getCertificate().getPublicKey());
    KeyAndCertCredential result = new KeyAndCertCredential(pair.getPrivate(), new X509Certificate[] { certificate, caCred.getCertificate() });
    return result;
}
Also used : KeyPair(java.security.KeyPair) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyPairGenerator(java.security.KeyPairGenerator) IOException(java.io.IOException) X500Name(org.bouncycastle.asn1.x500.X500Name) InvalidKeyException(java.security.InvalidKeyException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) Random(java.util.Random) X509v3CertificateBuilder(eu.emi.security.authn.x509.helpers.proxy.X509v3CertificateBuilder) KeyAndCertCredential(eu.emi.security.authn.x509.impl.KeyAndCertCredential) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger)

Aggregations

ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)99 IOException (java.io.IOException)81 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)34 ByteArrayInputStream (java.io.ByteArrayInputStream)28 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)22 BigInteger (java.math.BigInteger)20 ASN1InputStream (com.android.org.bouncycastle.asn1.ASN1InputStream)19 CertificateException (java.security.cert.CertificateException)19 X509Certificate (java.security.cert.X509Certificate)19 DEROctetString (org.bouncycastle.asn1.DEROctetString)19 CertificateParsingException (java.security.cert.CertificateParsingException)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)17 Enumeration (java.util.Enumeration)17 CertificateEncodingException (java.security.cert.CertificateEncodingException)16 InvalidKeyException (java.security.InvalidKeyException)14 CRLException (java.security.cert.CRLException)14 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)14 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)12 NoSuchProviderException (java.security.NoSuchProviderException)11 ASN1Primitive (org.bouncycastle.asn1.ASN1Primitive)11