Example usage for org.bouncycastle.asn1.x509 DSAParameter getInstance

List of usage examples for org.bouncycastle.asn1.x509 DSAParameter getInstance

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 DSAParameter getInstance.

Prototype

public static DSAParameter getInstance(Object obj) 

Source Link

Usage

From source file:net.jradius.client.auth.EAPTLSAuthenticator.java

License:Open Source License

/**
 * Create a private key parameter from the passed in PKCS8 PrivateKeyInfo object.
 * //from  www.  j ava 2  s. c o  m
 * @param keyInfo the PrivateKeyInfo object containing the key material
 * @return a suitable private key parameter
 * @throws IOException on an error decoding the key
 */
public static AsymmetricKeyParameter createKey(PrivateKeyInfo keyInfo) throws IOException {
    AlgorithmIdentifier algId = keyInfo.getAlgorithmId();

    if (algId.getObjectId().equals(PKCSObjectIdentifiers.rsaEncryption)) {
        RSAPrivateKeyStructure keyStructure = new RSAPrivateKeyStructure(
                (ASN1Sequence) keyInfo.getPrivateKey());

        return new RSAPrivateCrtKeyParameters(keyStructure.getModulus(), keyStructure.getPublicExponent(),
                keyStructure.getPrivateExponent(), keyStructure.getPrime1(), keyStructure.getPrime2(),
                keyStructure.getExponent1(), keyStructure.getExponent2(), keyStructure.getCoefficient());
    } else if (algId.getObjectId().equals(PKCSObjectIdentifiers.dhKeyAgreement)) {
        DHParameter params = new DHParameter((ASN1Sequence) keyInfo.getAlgorithmId().getParameters());
        DERInteger derX = (DERInteger) keyInfo.getPrivateKey();

        BigInteger lVal = params.getL();
        int l = lVal == null ? 0 : lVal.intValue();
        DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l);

        return new DHPrivateKeyParameters(derX.getValue(), dhParams);
    } else if (algId.getObjectId().equals(OIWObjectIdentifiers.elGamalAlgorithm)) {
        ElGamalParameter params = new ElGamalParameter((ASN1Sequence) keyInfo.getAlgorithmId().getParameters());
        DERInteger derX = (DERInteger) keyInfo.getPrivateKey();

        return new ElGamalPrivateKeyParameters(derX.getValue(),
                new ElGamalParameters(params.getP(), params.getG()));
    } else if (algId.getObjectId().equals(X9ObjectIdentifiers.id_dsa)) {
        DERInteger derX = (DERInteger) keyInfo.getPrivateKey();
        DEREncodable de = keyInfo.getAlgorithmId().getParameters();

        DSAParameters parameters = null;
        if (de != null) {
            DSAParameter params = DSAParameter.getInstance(de.getDERObject());
            parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
        }

        return new DSAPrivateKeyParameters(derX.getValue(), parameters);
    } else if (algId.getObjectId().equals(X9ObjectIdentifiers.id_ecPublicKey)) {
        X962Parameters params = new X962Parameters((DERObject) keyInfo.getAlgorithmId().getParameters());
        ECDomainParameters dParams = null;

        if (params.isNamedCurve()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) params.getParameters();
            X9ECParameters ecP = X962NamedCurves.getByOID(oid);

            if (ecP == null) {
                ecP = SECNamedCurves.getByOID(oid);

                if (ecP == null) {
                    ecP = NISTNamedCurves.getByOID(oid);

                    if (ecP == null) {
                        ecP = TeleTrusTNamedCurves.getByOID(oid);
                    }
                }
            }

            dParams = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed());
        } else {
            X9ECParameters ecP = new X9ECParameters((ASN1Sequence) params.getParameters());
            dParams = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed());
        }

        ECPrivateKeyStructure ec = new ECPrivateKeyStructure((ASN1Sequence) keyInfo.getPrivateKey());

        return new ECPrivateKeyParameters(ec.getKey(), dParams);
    } else {
        throw new RuntimeException("algorithm identifier in key not recognised");
    }
}

From source file:org.jruby.ext.openssl.impl.pem.MiscPEMGenerator.java

License:Open Source License

private PemObject createPemObject(Object o) throws IOException {
    String type;/*  w w  w.j a v  a2 s .c o m*/
    byte[] encoding;

    if (o instanceof PemObject) {
        return (PemObject) o;
    }
    if (o instanceof PemObjectGenerator) {
        return ((PemObjectGenerator) o).generate();
    }
    if (o instanceof X509CertificateHolder) {
        type = "CERTIFICATE";
        encoding = ((X509CertificateHolder) o).getEncoded();
    } else if (o instanceof X509CRLHolder) {
        type = "X509 CRL";
        encoding = ((X509CRLHolder) o).getEncoded();
    } else if (o instanceof PrivateKeyInfo) {
        PrivateKeyInfo info = (PrivateKeyInfo) o;
        ASN1ObjectIdentifier algOID = info.getPrivateKeyAlgorithm().getAlgorithm();

        if (algOID.equals(PKCSObjectIdentifiers.rsaEncryption)) {
            type = "RSA PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else if (algOID.equals(dsaOids[0]) || algOID.equals(dsaOids[1])) {
            type = "DSA PRIVATE KEY";

            DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();

            v.add(new ASN1Integer(BigInteger.ZERO));
            v.add(new ASN1Integer(p.getP()));
            v.add(new ASN1Integer(p.getQ()));
            v.add(new ASN1Integer(p.getG()));

            BigInteger x = ASN1Integer.getInstance(info.parsePrivateKey()).getValue();
            BigInteger y = p.getG().modPow(x, p.getP());

            v.add(new ASN1Integer(y));
            v.add(new ASN1Integer(x));

            encoding = new DERSequence(v).getEncoded();
        } else if (algOID.equals(X9ObjectIdentifiers.id_ecPublicKey)) {
            type = "EC PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof SubjectPublicKeyInfo) {
        type = "PUBLIC KEY";
        encoding = ((SubjectPublicKeyInfo) o).getEncoded();
    } else if (o instanceof X509AttributeCertificateHolder) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509AttributeCertificateHolder) o).getEncoded();
    } else if (o instanceof PKCS10CertificationRequest) {
        type = "CERTIFICATE REQUEST";
        encoding = ((PKCS10CertificationRequest) o).getEncoded();
    } else if (o instanceof ContentInfo) {
        type = "PKCS7";
        encoding = ((ContentInfo) o).getEncoded();
    }
    //
    // NOTE: added behaviour to provide backwards compatibility with 1.47 :
    //
    else if (o instanceof java.security.cert.X509Certificate) // 1.47 compatibility
    {
        type = "CERTIFICATE";
        try {
            encoding = ((java.security.cert.X509Certificate) o).getEncoded();
        } catch (CertificateEncodingException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof java.security.cert.X509CRL) // 1.47 compatibility
    {
        type = "X509 CRL";
        try {
            encoding = ((java.security.cert.X509CRL) o).getEncoded();
        } catch (CRLException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof java.security.KeyPair) // 1.47 compatibility
    {
        return createPemObject(((java.security.KeyPair) o).getPrivate());
    } else if (o instanceof java.security.PrivateKey) // 1.47 compatibility
    {
        PrivateKeyInfo info = new PrivateKeyInfo(
                (ASN1Sequence) ASN1Primitive.fromByteArray(((java.security.Key) o).getEncoded()));

        if (o instanceof java.security.interfaces.RSAPrivateKey) {
            type = "RSA PRIVATE KEY";

            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else if (o instanceof java.security.interfaces.DSAPrivateKey) {
            type = "DSA PRIVATE KEY";

            DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();

            v.add(new DERInteger(0));
            v.add(new DERInteger(p.getP()));
            v.add(new DERInteger(p.getQ()));
            v.add(new DERInteger(p.getG()));

            BigInteger x = ((java.security.interfaces.DSAPrivateKey) o).getX();
            BigInteger y = p.getG().modPow(x, p.getP());

            v.add(new DERInteger(y));
            v.add(new DERInteger(x));

            encoding = new DERSequence(v).getEncoded();
        } else if (((java.security.PrivateKey) o).getAlgorithm().equals("ECDSA")) {
            type = "EC PRIVATE KEY";

            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof java.security.PublicKey) // 1.47 compatibility
    {
        type = "PUBLIC KEY";

        encoding = ((java.security.PublicKey) o).getEncoded();
    } else if (o instanceof X509AttributeCertificate) // 1.47 compatibility
    {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509AttributeCertificate) o).getEncoded();
    }
    //
    //
    //
    else {
        throw new PemGenerationException("unknown object passed - can't encode.");
    }

    if (encryptor != null) // NEW STUFF (NOT IN OLD)
    {
        String dekAlgName = Strings.toUpperCase(encryptor.getAlgorithm());

        // Note: For backward compatibility
        if (dekAlgName.equals("DESEDE")) {
            dekAlgName = "DES-EDE3-CBC";
        }

        byte[] iv = encryptor.getIV();
        byte[] encData = encryptor.encrypt(encoding);

        List<PemHeader> headers = new ArrayList<PemHeader>(2);

        headers.add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
        headers.add(new PemHeader("DEK-Info", dekAlgName + "," + getHexEncoded(iv)));

        return new PemObject(type, headers, encData);
    }
    return new PemObject(type, encoding);
}

From source file:org.jruby.ext.openssl.x509store.BouncyCastleASN1FormatHandler.java

License:LGPL

@Override
public void writeDSAPrivateKey(Writer _out, DSAPrivateKey obj, String algo, char[] f) throws IOException {
    BufferedWriter out = makeBuffered(_out);
    ByteArrayInputStream bIn = new ByteArrayInputStream(getEncoded(obj));
    ASN1InputStream aIn = new ASN1InputStream(bIn);
    PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) aIn.readObject());
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream aOut = new ASN1OutputStream(bOut);

    DSAParameter p = DSAParameter.getInstance(info.getAlgorithmId().getParameters());
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(new DERInteger(0));
    v.add(new DERInteger(p.getP()));
    v.add(new DERInteger(p.getQ()));
    v.add(new DERInteger(p.getG()));

    BigInteger x = obj.getX();//from ww w  . j ava  2s .  c o m
    BigInteger y = p.getG().modPow(x, p.getP());

    v.add(new DERInteger(y));
    v.add(new DERInteger(x));

    aOut.writeObject(new DERSequence(v));
    byte[] encoding = bOut.toByteArray();

    if (algo != null && f != null) {
        byte[] salt = new byte[8];
        byte[] encData = null;
        random.nextBytes(salt);
        OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator();
        pGen.init(PBEParametersGenerator.PKCS5PasswordToBytes(f), salt);
        SecretKey secretKey = null;
        if (algo.equalsIgnoreCase("DESede/CBC/PKCS5Padding")) {
            // generate key
            int keyLength = 24;
            KeyParameter param = (KeyParameter) pGen.generateDerivedParameters(keyLength * 8);
            secretKey = new SecretKeySpec(param.getKey(), "DESede");
        } else {
            throw new IOException("unknown algorithm in write_DSAPrivateKey: " + algo);
        }

        // cipher  
        try {
            Cipher c = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            c.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(salt));
            encData = c.doFinal(encoding);
        } catch (Exception e) {
            throw new IOException("exception using cipher: " + e.toString());
        }

        // write the data
        out.write(BEF_G + PEM_STRING_DSA + AFT);
        out.newLine();
        out.write("Proc-Type: 4,ENCRYPTED");
        out.newLine();
        out.write("DEK-Info: DES-EDE3-CBC,");
        writeHexEncoded(out, salt);
        out.newLine();
        out.newLine();
        writeEncoded(out, encData);
        out.write(BEF_E + PEM_STRING_DSA + AFT);
        out.flush();
    } else {
        out.write(BEF_G + PEM_STRING_DSA + AFT);
        out.newLine();
        writeEncoded(out, encoding);
        out.write(BEF_E + PEM_STRING_DSA + AFT);
        out.newLine();
        out.flush();
    }
}

From source file:org.jruby.ext.openssl.x509store.PEMInputOutput.java

License:LGPL

public static void writeDSAPrivateKey(Writer _out, DSAPrivateKey obj, CipherSpec cipher, char[] passwd)
        throws IOException {
    BufferedWriter out = makeBuffered(_out);
    PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) new ASN1InputStream(getEncoded(obj)).readObject());
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream aOut = new ASN1OutputStream(bOut);

    DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(0));
    v.add(new ASN1Integer(p.getP()));
    v.add(new ASN1Integer(p.getQ()));
    v.add(new ASN1Integer(p.getG()));

    BigInteger x = obj.getX();/* w w w . j  a v  a  2s  .  c o  m*/
    BigInteger y = p.getG().modPow(x, p.getP());

    v.add(new ASN1Integer(y));
    v.add(new ASN1Integer(x));

    aOut.writeObject(new DLSequence(v));
    byte[] encoding = bOut.toByteArray();

    if (cipher != null && passwd != null) {
        writePemEncrypted(out, PEM_STRING_DSA, encoding, cipher, passwd);
    } else {
        writePemPlain(out, PEM_STRING_DSA, encoding);
    }
}

From source file:org.usrz.libs.crypto.pem.PEMFactory.java

License:Apache License

public PrivateKey getPrivateKey(PrivateKeyInfo keyInfo)
        throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {

    final Object algorithmId = keyInfo.getPrivateKeyAlgorithm().getAlgorithm();
    final ASN1Encodable encodable;
    try {/*from  w w  w  .j  a v  a 2  s. c  o m*/
        encodable = keyInfo.parsePrivateKey();
    } catch (IOException exception) {
        throw new InvalidKeyException("Unable to parse private key structure", exception);
    }

    /* DSA keys */
    if (algorithmId.equals(X9ObjectIdentifiers.id_dsa)) {
        final ASN1Encodable encodedParams = keyInfo.getPrivateKeyAlgorithm().getParameters();
        final DSAParameter params = DSAParameter.getInstance(encodedParams);
        final BigInteger x = ASN1Integer.getInstance(encodable).getValue();
        return getDSAKeyFactory()
                .generatePrivate(new DSAPrivateKeySpec(x, params.getP(), params.getQ(), params.getG()));
    }

    /* RSA keys */
    if (algorithmId.equals(PKCSObjectIdentifiers.rsaEncryption)) {
        final RSAPrivateKey privateKey = RSAPrivateKey.getInstance(encodable);
        return getRSAKeyFactory().generatePrivate(
                new RSAPrivateCrtKeySpec(privateKey.getModulus(), privateKey.getPublicExponent(),
                        privateKey.getPrivateExponent(), privateKey.getPrime1(), privateKey.getPrime2(),
                        privateKey.getExponent1(), privateKey.getExponent2(), privateKey.getCoefficient()));
    }

    /* Others? */
    throw new NoSuchAlgorithmException("Unsupported algorithm for private key: " + algorithmId);

}

From source file:org.xipki.commons.security.util.X509Util.java

License:Open Source License

public static SubjectPublicKeyInfo toRfc3279Style(final SubjectPublicKeyInfo publicKeyInfo)
        throws InvalidKeySpecException {
    ParamUtil.requireNonNull("publicKeyInfo", publicKeyInfo);
    ASN1ObjectIdentifier algOid = publicKeyInfo.getAlgorithm().getAlgorithm();
    ASN1Encodable keyParameters = publicKeyInfo.getAlgorithm().getParameters();

    if (PKCSObjectIdentifiers.rsaEncryption.equals(algOid)) {
        if (DERNull.INSTANCE.equals(keyParameters)) {
            return publicKeyInfo;
        } else {//from  ww  w  .ja  va 2s  . c  o  m
            AlgorithmIdentifier keyAlgId = new AlgorithmIdentifier(algOid, DERNull.INSTANCE);
            return new SubjectPublicKeyInfo(keyAlgId, publicKeyInfo.getPublicKeyData().getBytes());
        }
    } else if (X9ObjectIdentifiers.id_dsa.equals(algOid)) {
        if (keyParameters == null) {
            return publicKeyInfo;
        } else if (DERNull.INSTANCE.equals(keyParameters)) {
            AlgorithmIdentifier keyAlgId = new AlgorithmIdentifier(algOid);
            return new SubjectPublicKeyInfo(keyAlgId, publicKeyInfo.getPublicKeyData().getBytes());
        } else {
            try {
                DSAParameter.getInstance(keyParameters);
            } catch (IllegalArgumentException ex) {
                throw new InvalidKeySpecException("keyParameters is not null and Dss-Parms");
            }
            return publicKeyInfo;
        }
    } else if (X9ObjectIdentifiers.id_ecPublicKey.equals(algOid)) {
        if (keyParameters == null) {
            throw new InvalidKeySpecException("keyParameters is not an OBJECT IDENTIFIER");
        }
        try {
            ASN1ObjectIdentifier.getInstance(keyParameters);
        } catch (IllegalArgumentException ex) {
            throw new InvalidKeySpecException("keyParameters is not an OBJECT IDENTIFIER");
        }
        return publicKeyInfo;
    } else {
        return publicKeyInfo;
    }
}