Search in sources :

Example 1 with RSAPrivateKey

use of com.github.zhenwei.core.asn1.pkcs.RSAPrivateKey in project X-Road by nordic-institute.

the class CertUtils method readKeyPairFromPemFile.

/**
 * Read private and public keys from PEM file
 * @param filename file containing the keypair
 * @return KeyPair
 * @throws NoSuchAlgorithmException when algorithm for decoding is not available
 * @throws InvalidKeySpecException when key file is invalid
 * @throws IOException when I/O error occurs
 */
public static KeyPair readKeyPairFromPemFile(String filename) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
    File pkFile = new File(filename);
    try (PEMParser pemParser = new PEMParser(new FileReader(pkFile))) {
        Object o = pemParser.readObject();
        if (o == null || !(o instanceof PrivateKeyInfo)) {
            throw new CodedException(X_INTERNAL_ERROR, "Could not read key from '%s'", filename);
        }
        PrivateKeyInfo pki = (PrivateKeyInfo) o;
        KeyFactory kf = KeyFactory.getInstance("RSA");
        final PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(pki.getEncoded());
        final PrivateKey privateKey = kf.generatePrivate(ks);
        final RSAPrivateKey rpk = RSAPrivateKey.getInstance(pki.parsePrivateKey());
        final PublicKey publicKey = kf.generatePublic(new RSAPublicKeySpec(rpk.getModulus(), rpk.getPublicExponent()));
        KeyPair kp = new KeyPair(publicKey, privateKey);
        return kp;
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) RSAPrivateKey(org.bouncycastle.asn1.pkcs.RSAPrivateKey) PublicKey(java.security.PublicKey) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) PEMParser(org.bouncycastle.openssl.PEMParser) CodedException(ee.ria.xroad.common.CodedException) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) FileReader(java.io.FileReader) CryptoUtils.toDERObject(ee.ria.xroad.common.util.CryptoUtils.toDERObject) File(java.io.File) RSAPrivateKey(org.bouncycastle.asn1.pkcs.RSAPrivateKey) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) KeyFactory(java.security.KeyFactory)

Example 2 with RSAPrivateKey

use of com.github.zhenwei.core.asn1.pkcs.RSAPrivateKey in project robovm by robovm.

the class PrivateKeyFactory method createKey.

/**
     * Create a private key parameter from the passed in PKCS8 PrivateKeyInfo object.
     * 
     * @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.getPrivateKeyAlgorithm();
    if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.rsaEncryption)) {
        RSAPrivateKey keyStructure = RSAPrivateKey.getInstance(keyInfo.parsePrivateKey());
        return new RSAPrivateCrtKeyParameters(keyStructure.getModulus(), keyStructure.getPublicExponent(), keyStructure.getPrivateExponent(), keyStructure.getPrime1(), keyStructure.getPrime2(), keyStructure.getExponent1(), keyStructure.getExponent2(), keyStructure.getCoefficient());
    } else //      else if (algId.getObjectId().equals(X9ObjectIdentifiers.dhpublicnumber))
    if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.dhKeyAgreement)) {
        DHParameter params = DHParameter.getInstance(algId.getParameters());
        ASN1Integer derX = (ASN1Integer) keyInfo.parsePrivateKey();
        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 // END android-removed
    if (algId.getAlgorithm().equals(X9ObjectIdentifiers.id_dsa)) {
        ASN1Integer derX = (ASN1Integer) keyInfo.parsePrivateKey();
        ASN1Encodable de = algId.getParameters();
        DSAParameters parameters = null;
        if (de != null) {
            DSAParameter params = DSAParameter.getInstance(de.toASN1Primitive());
            parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
        }
        return new DSAPrivateKeyParameters(derX.getValue(), parameters);
    } else if (algId.getAlgorithm().equals(X9ObjectIdentifiers.id_ecPublicKey)) {
        X962Parameters params = new X962Parameters((ASN1Primitive) algId.getParameters());
        X9ECParameters x9;
        if (params.isNamedCurve()) {
            ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(params.getParameters());
            x9 = X962NamedCurves.getByOID(oid);
            if (x9 == null) {
                x9 = SECNamedCurves.getByOID(oid);
                if (x9 == null) {
                    x9 = NISTNamedCurves.getByOID(oid);
                // BEGIN android-removed
                // if (x9 == null)
                // {
                //     x9 = TeleTrusTNamedCurves.getByOID(oid);
                // }
                // END android-removed
                }
            }
        } else {
            x9 = X9ECParameters.getInstance(params.getParameters());
        }
        ECPrivateKey ec = ECPrivateKey.getInstance(keyInfo.parsePrivateKey());
        BigInteger d = ec.getKey();
        // TODO We lose any named parameters here
        ECDomainParameters dParams = new ECDomainParameters(x9.getCurve(), x9.getG(), x9.getN(), x9.getH(), x9.getSeed());
        return new ECPrivateKeyParameters(d, dParams);
    } else {
        throw new RuntimeException("algorithm identifier in key not recognised");
    }
}
Also used : ECPrivateKey(org.bouncycastle.asn1.sec.ECPrivateKey) ECDomainParameters(org.bouncycastle.crypto.params.ECDomainParameters) DHParameters(org.bouncycastle.crypto.params.DHParameters) DHPrivateKeyParameters(org.bouncycastle.crypto.params.DHPrivateKeyParameters) X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) X962Parameters(org.bouncycastle.asn1.x9.X962Parameters) ECPrivateKeyParameters(org.bouncycastle.crypto.params.ECPrivateKeyParameters) DSAPrivateKeyParameters(org.bouncycastle.crypto.params.DSAPrivateKeyParameters) BigInteger(java.math.BigInteger) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) RSAPrivateKey(org.bouncycastle.asn1.pkcs.RSAPrivateKey) DHParameter(org.bouncycastle.asn1.pkcs.DHParameter) DSAParameters(org.bouncycastle.crypto.params.DSAParameters) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) RSAPrivateCrtKeyParameters(org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters)

Example 3 with RSAPrivateKey

use of com.github.zhenwei.core.asn1.pkcs.RSAPrivateKey in project LinLong-Java by zhenwei1108.

the class RSAPrivateKey method toASN1Primitive.

/**
 * This outputs the key in PKCS1v2 format.
 * <pre>
 *      RSAPrivateKey ::= SEQUENCE {
 *                          version Version,
 *                          modulus INTEGER, -- n
 *                          publicExponent INTEGER, -- e
 *                          privateExponent INTEGER, -- d
 *                          prime1 INTEGER, -- p
 *                          prime2 INTEGER, -- q
 *                          exponent1 INTEGER, -- d mod (p-1)
 *                          exponent2 INTEGER, -- d mod (q-1)
 *                          coefficient INTEGER, -- (inverse of q) mod p
 *                          otherPrimeInfos OtherPrimeInfos OPTIONAL
 *                      }
 *
 *      Version ::= INTEGER { two-prime(0), multi(1) }
 *        (CONSTRAINED BY {-- version must be multi if otherPrimeInfos present --})
 * </pre>
 * <p>
 * This routine is written to output PKCS1 version 2.1, private keys.
 */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector(10);
    // version
    v.add(new ASN1Integer(version));
    v.add(new ASN1Integer(getModulus()));
    v.add(new ASN1Integer(getPublicExponent()));
    v.add(new ASN1Integer(getPrivateExponent()));
    v.add(new ASN1Integer(getPrime1()));
    v.add(new ASN1Integer(getPrime2()));
    v.add(new ASN1Integer(getExponent1()));
    v.add(new ASN1Integer(getExponent2()));
    v.add(new ASN1Integer(getCoefficient()));
    if (otherPrimeInfos != null) {
        v.add(otherPrimeInfos);
    }
    return new DERSequence(v);
}
Also used : DERSequence(com.github.zhenwei.core.asn1.DERSequence) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer)

Example 4 with RSAPrivateKey

use of com.github.zhenwei.core.asn1.pkcs.RSAPrivateKey in project LinLong-Java by zhenwei1108.

the class RSAPrivateKeyStructure method toASN1Primitive.

/**
 * This outputs the key in PKCS1v2 format.
 * <pre>
 *      RSAPrivateKey ::= SEQUENCE {
 *                          version Version,
 *                          modulus INTEGER, -- n
 *                          publicExponent INTEGER, -- e
 *                          privateExponent INTEGER, -- d
 *                          prime1 INTEGER, -- p
 *                          prime2 INTEGER, -- q
 *                          exponent1 INTEGER, -- d mod (p-1)
 *                          exponent2 INTEGER, -- d mod (q-1)
 *                          coefficient INTEGER, -- (inverse of q) mod p
 *                          otherPrimeInfos OtherPrimeInfos OPTIONAL
 *                      }
 *
 *      Version ::= INTEGER { two-prime(0), multi(1) }
 *        (CONSTRAINED BY {-- version must be multi if otherPrimeInfos present --})
 * </pre>
 * <p>
 * This routine is written to output PKCS1 version 2.1, private keys.
 */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector(10);
    // version
    v.add(new ASN1Integer(version));
    v.add(new ASN1Integer(getModulus()));
    v.add(new ASN1Integer(getPublicExponent()));
    v.add(new ASN1Integer(getPrivateExponent()));
    v.add(new ASN1Integer(getPrime1()));
    v.add(new ASN1Integer(getPrime2()));
    v.add(new ASN1Integer(getExponent1()));
    v.add(new ASN1Integer(getExponent2()));
    v.add(new ASN1Integer(getCoefficient()));
    if (otherPrimeInfos != null) {
        v.add(otherPrimeInfos);
    }
    return new DERSequence(v);
}
Also used : DERSequence(com.github.zhenwei.core.asn1.DERSequence) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer)

Example 5 with RSAPrivateKey

use of com.github.zhenwei.core.asn1.pkcs.RSAPrivateKey in project LinLong-Java by zhenwei1108.

the class PrivateKeyInfoFactory method createPrivateKeyInfo.

/**
 * Create a PrivateKeyInfo representation of a private key with attributes.
 *
 * @param privateKey the key to be encoded into the info object.
 * @param attributes the set of attributes to be included.
 * @return the appropriate PrivateKeyInfo
 * @throws IOException on an error encoding the key
 */
public static PrivateKeyInfo createPrivateKeyInfo(AsymmetricKeyParameter privateKey, ASN1Set attributes) throws IOException {
    if (privateKey instanceof RSAKeyParameters) {
        RSAPrivateCrtKeyParameters priv = (RSAPrivateCrtKeyParameters) privateKey;
        return new PrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPrivateKey(priv.getModulus(), priv.getPublicExponent(), priv.getExponent(), priv.getP(), priv.getQ(), priv.getDP(), priv.getDQ(), priv.getQInv()), attributes);
    } else if (privateKey instanceof DSAPrivateKeyParameters) {
        DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters) privateKey;
        DSAParameters params = priv.getParameters();
        return new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(params.getP(), params.getQ(), params.getG())), new ASN1Integer(priv.getX()), attributes);
    } else if (privateKey instanceof ECPrivateKeyParameters) {
        ECPrivateKeyParameters priv = (ECPrivateKeyParameters) privateKey;
        ECDomainParameters domainParams = priv.getParameters();
        ASN1Encodable params;
        int orderBitLength;
        if (domainParams == null) {
            // Implicitly CA
            params = new X962Parameters(DERNull.INSTANCE);
            orderBitLength = priv.getD().bitLength();
        } else if (domainParams instanceof ECGOST3410Parameters) {
            GOST3410PublicKeyAlgParameters gostParams = new GOST3410PublicKeyAlgParameters(((ECGOST3410Parameters) domainParams).getPublicKeyParamSet(), ((ECGOST3410Parameters) domainParams).getDigestParamSet(), ((ECGOST3410Parameters) domainParams).getEncryptionParamSet());
            int size;
            ASN1ObjectIdentifier identifier;
            if (cryptoProOids.contains(gostParams.getPublicKeyParamSet())) {
                size = 32;
                identifier = CryptoProObjectIdentifiers.gostR3410_2001;
            } else {
                boolean is512 = priv.getD().bitLength() > 256;
                identifier = (is512) ? RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512 : RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256;
                size = (is512) ? 64 : 32;
            }
            byte[] encKey = new byte[size];
            extractBytes(encKey, size, 0, priv.getD());
            return new PrivateKeyInfo(new AlgorithmIdentifier(identifier, gostParams), new DEROctetString(encKey));
        } else if (domainParams instanceof ECNamedDomainParameters) {
            params = new X962Parameters(((ECNamedDomainParameters) domainParams).getName());
            orderBitLength = domainParams.getN().bitLength();
        } else {
            X9ECParameters ecP = new X9ECParameters(domainParams.getCurve(), new X9ECPoint(domainParams.getG(), false), domainParams.getN(), domainParams.getH(), domainParams.getSeed());
            params = new X962Parameters(ecP);
            orderBitLength = domainParams.getN().bitLength();
        }
        ECPoint q = new FixedPointCombMultiplier().multiply(domainParams.getG(), priv.getD());
        // TODO Support point compression
        DERBitString publicKey = new DERBitString(q.getEncoded(false));
        return new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params), new ECPrivateKey(orderBitLength, priv.getD(), publicKey, params), attributes);
    } else if (privateKey instanceof X448PrivateKeyParameters) {
        X448PrivateKeyParameters key = (X448PrivateKeyParameters) privateKey;
        return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X448), new DEROctetString(key.getEncoded()), attributes, key.generatePublicKey().getEncoded());
    } else if (privateKey instanceof X25519PrivateKeyParameters) {
        X25519PrivateKeyParameters key = (X25519PrivateKeyParameters) privateKey;
        return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X25519), new DEROctetString(key.getEncoded()), attributes, key.generatePublicKey().getEncoded());
    } else if (privateKey instanceof Ed448PrivateKeyParameters) {
        Ed448PrivateKeyParameters key = (Ed448PrivateKeyParameters) privateKey;
        return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed448), new DEROctetString(key.getEncoded()), attributes, key.generatePublicKey().getEncoded());
    } else if (privateKey instanceof Ed25519PrivateKeyParameters) {
        Ed25519PrivateKeyParameters key = (Ed25519PrivateKeyParameters) privateKey;
        return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519), new DEROctetString(key.getEncoded()), attributes, key.generatePublicKey().getEncoded());
    } else {
        throw new IOException("key parameters not recognized");
    }
}
Also used : ECDomainParameters(com.github.zhenwei.core.crypto.params.ECDomainParameters) X9ECParameters(com.github.zhenwei.core.asn1.x9.X9ECParameters) ECGOST3410Parameters(com.github.zhenwei.core.crypto.params.ECGOST3410Parameters) GOST3410PublicKeyAlgParameters(com.github.zhenwei.core.asn1.cryptopro.GOST3410PublicKeyAlgParameters) X25519PrivateKeyParameters(com.github.zhenwei.core.crypto.params.X25519PrivateKeyParameters) Ed448PrivateKeyParameters(com.github.zhenwei.core.crypto.params.Ed448PrivateKeyParameters) Ed25519PrivateKeyParameters(com.github.zhenwei.core.crypto.params.Ed25519PrivateKeyParameters) RSAKeyParameters(com.github.zhenwei.core.crypto.params.RSAKeyParameters) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) X962Parameters(com.github.zhenwei.core.asn1.x9.X962Parameters) FixedPointCombMultiplier(com.github.zhenwei.core.math.ec.FixedPointCombMultiplier) DSAParameter(com.github.zhenwei.core.asn1.x509.DSAParameter) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) X448PrivateKeyParameters(com.github.zhenwei.core.crypto.params.X448PrivateKeyParameters) ECPrivateKey(com.github.zhenwei.core.asn1.sec.ECPrivateKey) ECNamedDomainParameters(com.github.zhenwei.core.crypto.params.ECNamedDomainParameters) DERBitString(com.github.zhenwei.core.asn1.DERBitString) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) IOException(java.io.IOException) ECPoint(com.github.zhenwei.core.math.ec.ECPoint) X9ECPoint(com.github.zhenwei.core.asn1.x9.X9ECPoint) ECPoint(com.github.zhenwei.core.math.ec.ECPoint) X9ECPoint(com.github.zhenwei.core.asn1.x9.X9ECPoint) ECPrivateKeyParameters(com.github.zhenwei.core.crypto.params.ECPrivateKeyParameters) X9ECPoint(com.github.zhenwei.core.asn1.x9.X9ECPoint) DSAPrivateKeyParameters(com.github.zhenwei.core.crypto.params.DSAPrivateKeyParameters) RSAPrivateKey(com.github.zhenwei.core.asn1.pkcs.RSAPrivateKey) DSAParameters(com.github.zhenwei.core.crypto.params.DSAParameters) PrivateKeyInfo(com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) RSAPrivateCrtKeyParameters(com.github.zhenwei.core.crypto.params.RSAPrivateCrtKeyParameters)

Aggregations

RSAPrivateKey (org.bouncycastle.asn1.pkcs.RSAPrivateKey)6 ASN1Integer (com.github.zhenwei.core.asn1.ASN1Integer)5 BigInteger (java.math.BigInteger)5 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)3 RSAPrivateKey (com.github.zhenwei.core.asn1.pkcs.RSAPrivateKey)3 ECPrivateKey (com.github.zhenwei.core.asn1.sec.ECPrivateKey)3 X9ECParameters (com.github.zhenwei.core.asn1.x9.X9ECParameters)3 DSAParameters (com.github.zhenwei.core.crypto.params.DSAParameters)3 DSAPrivateKeyParameters (com.github.zhenwei.core.crypto.params.DSAPrivateKeyParameters)3 ECNamedDomainParameters (com.github.zhenwei.core.crypto.params.ECNamedDomainParameters)3 ECPrivateKeyParameters (com.github.zhenwei.core.crypto.params.ECPrivateKeyParameters)3 Ed25519PrivateKeyParameters (com.github.zhenwei.core.crypto.params.Ed25519PrivateKeyParameters)3 RSAPrivateCrtKeyParameters (com.github.zhenwei.core.crypto.params.RSAPrivateCrtKeyParameters)3 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)3 ASN1Encodable (com.github.zhenwei.core.asn1.ASN1Encodable)2 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)2 ASN1Sequence (com.github.zhenwei.core.asn1.ASN1Sequence)2 DERSequence (com.github.zhenwei.core.asn1.DERSequence)2 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)2 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)2