Search in sources :

Example 1 with KeyAlgorithms

use of org.webpki.crypto.KeyAlgorithms in project openkeystore by cyberphone.

the class CommandLineCA method eccCurves.

String eccCurves() {
    StringBuilder s = new StringBuilder();
    boolean comma = false;
    for (KeyAlgorithms curve : KeyAlgorithms.values()) {
        if (curve.getKeyType() != KeyTypes.RSA) {
            if (comma) {
                s.append(", ");
            }
            comma = true;
            s.append(curve.toString());
        }
    }
    return s.toString();
}
Also used : KeyAlgorithms(org.webpki.crypto.KeyAlgorithms)

Example 2 with KeyAlgorithms

use of org.webpki.crypto.KeyAlgorithms in project openkeystore by cyberphone.

the class CommandLineCA method decodeCommandLine.

void decodeCommandLine(String[] argv) throws IOException {
    if (argv.length == 0) {
        show();
        System.exit(3);
    }
    for (int i = 0; i < argv.length; i++) {
        String arg = argv[i];
        if (arg.indexOf('-') != 0) {
            bad("Command '" + arg + "' MUST start with a '-'");
        }
        CmdLineArgument cla = get(arg);
        if (cla.optargument == null)
            continue;
        if (++i >= argv.length) {
            bad("Missing argument for command: " + arg);
        }
        String opt = argv[i];
        if (opt.indexOf('-') == 0) {
            bad("Argument to command '" + arg + "' MUST NOT start with a '-'");
        }
        cla.argvalue.add(opt);
    }
    checkConsistency();
    try {
        CA ca = new CA();
        CertSpec certspec = new CertSpec();
        // /////////////////////////////////////////////////////////////
        // Create the target certificate key-pair
        // /////////////////////////////////////////////////////////////
        KeyPairGenerator kpg = null;
        if (CMD_ecc_curve.found) {
            KeyAlgorithms keyAlgorithm = CMD_ecc_curve.getKeyAlgorithm();
            if (keyAlgorithm.getKeyType() == KeyTypes.EC) {
                kpg = KeyPairGenerator.getInstance("EC");
                kpg.initialize(new ECGenParameterSpec(keyAlgorithm.getJceName()));
            } else {
                kpg = KeyPairGenerator.getInstance(keyAlgorithm.getJceName());
            }
        } else {
            kpg = KeyPairGenerator.getInstance("RSA");
            if (CMD_exponent.found) {
                kpg.initialize(new RSAKeyGenParameterSpec(CMD_rsa_key_size.getInteger(), BigInteger.valueOf(CMD_exponent.getInteger())));
            } else {
                kpg.initialize(CMD_rsa_key_size.getInteger());
            }
        }
        KeyPair key_pair = kpg.generateKeyPair();
        PrivateKey priv_key = key_pair.getPrivate();
        PublicKey subject_pub_key = key_pair.getPublic();
        // /////////////////////////////////////////////////////////////
        // Get signature algorithm
        // /////////////////////////////////////////////////////////////
        AsymSignatureAlgorithms certalg = CMD_sig_alg.getAlgorithm();
        // /////////////////////////////////////////////////////////////
        // Get the subject DN
        // /////////////////////////////////////////////////////////////
        certspec.setSubject(CMD_subject_dn.getString());
        // /////////////////////////////////////////////////////////////
        // Get the signing key and CA certificate(s)
        // /////////////////////////////////////////////////////////////
        // Assume self-signed
        PrivateKey sign_key = priv_key;
        PublicKey issuer_pub_key = subject_pub_key;
        DistinguishedName issuer = certspec.getSubjectDistinguishedName();
        ArrayList<Certificate> cert_path = new ArrayList<>();
        if (!CMD_self_signed.found) {
            KeyStore ks = KeyStore.getInstance(CMD_ca_ks_type.getString());
            ks.load(new FileInputStream(CMD_ca_keystore.getString()), CMD_ca_ks_pass.toCharArray());
            String ca_key_alias = CMD_ca_key_alias.getString();
            if (ks.isKeyEntry(ca_key_alias)) {
                Certificate[] cert_list = ks.getCertificateChain(ca_key_alias);
                if (cert_list == null || cert_list.length == 0) {
                    bad("No certficates found for key alias: " + ca_key_alias);
                }
                issuer = DistinguishedName.subjectDN((X509Certificate) cert_list[0]);
                issuer_pub_key = cert_list[0].getPublicKey();
                if (CMD_ca_addpath.found) {
                    int n = cert_list.length;
                    if (!CMD_ca_addpath.getString().equals("all")) {
                        int l = CMD_ca_addpath.getInteger();
                        if (l < 1 || l > n) {
                            bad("The \"ca/addpath\" qualifier is out of range");
                        }
                        n = l;
                    }
                    for (int q = 0; q < n; q++) {
                        cert_path.add(cert_list[q]);
                    }
                }
            } else {
                bad("Bad CA key alias: " + ca_key_alias);
            }
            sign_key = (PrivateKey) ks.getKey(ca_key_alias, CMD_ca_key_pass.toCharArray());
            if (sign_key == null) {
                bad("No signature key found for key alias: " + ca_key_alias);
            }
        }
        // /////////////////////////////////////////////////////////////
        // Get serial number
        // /////////////////////////////////////////////////////////////
        BigInteger serial = CMD_serial.found ? CMD_serial.getBigInteger() : createSerial();
        // /////////////////////////////////////////////////////////////
        // Get validity
        // /////////////////////////////////////////////////////////////
        Date start_date = CMD_valid_start.getDateTime();
        Date end_date = CMD_valid_end.getDateTime();
        // /////////////////////////////////////////////////////////////
        if (CMD_ca_cert.found) {
            certspec.setCACertificateConstraint();
        } else if (CMD_ee_cert.found) {
            certspec.setEndEntityConstraint();
        }
        // /////////////////////////////////////////////////////////////
        for (String arg : CMD_key_usage.argvalue) {
            certspec.setKeyUsageBit(KeyUsageBits.getKeyUsageBit(arg));
        }
        // /////////////////////////////////////////////////////////////
        for (String arg : CMD_ext_eku.argvalue) {
            certspec.setExtendedKeyUsage(ExtendedKeyUsages.getExtendedKeyUsage(arg));
        }
        // /////////////////////////////////////////////////////////////
        if (CMD_ext_ski.found) {
            certspec.setSubjectKeyIdentifier();
        }
        // /////////////////////////////////////////////////////////////
        if (CMD_ext_aki.found) {
            certspec.setAuthorityKeyIdentifier();
        }
        // /////////////////////////////////////////////////////////////
        for (String arg : CMD_ext_certpol.argvalue) {
            certspec.addCertificatePolicyOID(arg);
        }
        // /////////////////////////////////////////////////////////////
        for (String arg : CMD_ext_ocsp.argvalue) {
            certspec.addOCSPResponderURI(arg);
        }
        // /////////////////////////////////////////////////////////////
        for (String arg : CMD_ext_caissuers.argvalue) {
            certspec.addCAIssuersURI(arg);
        }
        // /////////////////////////////////////////////////////////////
        for (String arg : CMD_ext_cdp.argvalue) {
            certspec.addCRLDistributionPointURI(arg);
        }
        // /////////////////////////////////////////////////////////////
        for (String arg : CMD_ext_email.argvalue) {
            certspec.addEmailAddress(arg);
        }
        // /////////////////////////////////////////////////////////////
        for (String arg : CMD_ext_dns.argvalue) {
            certspec.addDNSName(arg);
        }
        // /////////////////////////////////////////////////////////////
        for (String arg : CMD_ext_ip.argvalue) {
            certspec.addIPAddress(arg);
        }
        // /////////////////////////////////////////////////////////////
        // And now: Create the certificate path...
        // /////////////////////////////////////////////////////////////
        X509Certificate signer_cert = ca.createCert(certspec, issuer, serial, start_date, end_date, new CertificateSigner(sign_key, certalg), issuer_pub_key, subject_pub_key);
        cert_path.add(0, signer_cert);
        // /////////////////////////////////////////////////////////////
        // The final: Write the whole thing out
        // /////////////////////////////////////////////////////////////
        KeyStore ks = KeyStore.getInstance(CMD_out_ks_type.getString());
        if (CMD_out_update.found) {
            ks.load(new FileInputStream(CMD_out_keystore.getString()), CMD_out_ks_pass.toCharArray());
        } else {
            ks.load(null, null);
        }
        FileOutputStream ofile = new FileOutputStream(CMD_out_keystore.getString());
        ks.setKeyEntry(CMD_out_key_alias.getString(), priv_key, CMD_out_pkey_pass.toCharArray(), cert_path.toArray(new Certificate[0]));
        ks.store(ofile, CMD_out_ks_pass.toCharArray());
    } catch (GeneralSecurityException gse) {
        bad(gse.getMessage());
    }
}
Also used : PrivateKey(java.security.PrivateKey) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) ArrayList(java.util.ArrayList) RSAKeyGenParameterSpec(java.security.spec.RSAKeyGenParameterSpec) KeyAlgorithms(org.webpki.crypto.KeyAlgorithms) KeyPair(java.security.KeyPair) DistinguishedName(org.webpki.asn1.cert.DistinguishedName) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) KeyPairGenerator(java.security.KeyPairGenerator) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) FileOutputStream(java.io.FileOutputStream) BigInteger(java.math.BigInteger) AsymSignatureAlgorithms(org.webpki.crypto.AsymSignatureAlgorithms) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 3 with KeyAlgorithms

use of org.webpki.crypto.KeyAlgorithms in project openkeystore by cyberphone.

the class CBORPublicKey method encode.

/**
 * Converts JCE public key to COSE.
 *
 * @param jcePublicKey in Java/JCE format
 * @return Public key in COSE format
 * @throws IOException
 * @throws GeneralSecurityException
 */
public static CBORMap encode(PublicKey jcePublicKey) throws IOException, GeneralSecurityException {
    CBORMap cosePublicKey = new CBORMap();
    KeyAlgorithms keyAlg = KeyAlgorithms.getKeyAlgorithm(jcePublicKey);
    switch(keyAlg.getKeyType()) {
        case RSA:
            RSAPublicKey rsaPublicKey = (RSAPublicKey) jcePublicKey;
            cosePublicKey.setObject(COSE_KTY_LABEL, COSE_RSA_KTY).setByteString(COSE_RSA_N_LABEL, cryptoBinary(rsaPublicKey.getModulus())).setByteString(COSE_RSA_E_LABEL, cryptoBinary(rsaPublicKey.getPublicExponent()));
            break;
        case EC:
            ECPoint ecPoint = ((ECPublicKey) jcePublicKey).getW();
            cosePublicKey.setObject(COSE_KTY_LABEL, COSE_EC2_KTY).setObject(COSE_EC2_CRV_LABEL, WEBPKI_2_COSE_CRV.get(keyAlg)).setByteString(COSE_EC2_X_LABEL, curvePoint(ecPoint.getAffineX(), keyAlg)).setByteString(COSE_EC2_Y_LABEL, curvePoint(ecPoint.getAffineY(), keyAlg));
            break;
        default:
            // EDDSA and XEC
            cosePublicKey.setObject(COSE_KTY_LABEL, COSE_OKP_KTY).setObject(COSE_OKP_CRV_LABEL, WEBPKI_2_COSE_CRV.get(keyAlg)).setByteString(COSE_OKP_X_LABEL, OkpSupport.public2RawOkpKey(jcePublicKey, keyAlg));
    }
    return cosePublicKey;
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) KeyAlgorithms(org.webpki.crypto.KeyAlgorithms) ECPoint(java.security.spec.ECPoint)

Example 4 with KeyAlgorithms

use of org.webpki.crypto.KeyAlgorithms in project openkeystore by cyberphone.

the class CBORPublicKey method decode.

/**
 * Converts COSE public key to JCE.
 *
 * @param cosePublicKey Public key in COSE format
 * @return Public key as a Java/JCE object
 * @throws IOException
 * @throws GeneralSecurityException
 */
public static PublicKey decode(CBORObject cosePublicKey) throws IOException, GeneralSecurityException {
    CBORMap publicKeyMap = cosePublicKey.getMap();
    int coseKty = publicKeyMap.getObject(COSE_KTY_LABEL).getInt();
    KeyTypes keyType = keyTypes.get(coseKty);
    if (keyType == null) {
        throw new GeneralSecurityException("Unrecognized key type: " + coseKty);
    }
    KeyAlgorithms keyAlg;
    PublicKey publicKey;
    switch(keyType) {
        case RSA:
            publicKey = KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(getCryptoBinary(publicKeyMap.getObject(COSE_RSA_N_LABEL)), getCryptoBinary(publicKeyMap.getObject(COSE_RSA_E_LABEL))));
            break;
        case EC:
            keyAlg = getKeyAlgorithmFromCurveId(publicKeyMap.getObject(COSE_EC2_CRV_LABEL));
            if (keyAlg.getKeyType() != KeyTypes.EC) {
                throw new GeneralSecurityException("Invalid EC curve: " + keyAlg.toString());
            }
            publicKey = KeyFactory.getInstance("EC").generatePublic(new ECPublicKeySpec(new ECPoint(getCurvePoint(publicKeyMap.getObject(COSE_EC2_X_LABEL), keyAlg), getCurvePoint(publicKeyMap.getObject(COSE_EC2_Y_LABEL), keyAlg)), keyAlg.getECParameterSpec()));
            break;
        default:
            // EDDSA and XEC
            keyAlg = getKeyAlgorithmFromCurveId(publicKeyMap.getObject(COSE_OKP_CRV_LABEL));
            if (keyAlg.getKeyType() != KeyTypes.EDDSA && keyAlg.getKeyType() != KeyTypes.XEC) {
                throw new GeneralSecurityException("Invalid OKP curve: " + keyAlg.toString());
            }
            publicKey = OkpSupport.raw2PublicOkpKey(publicKeyMap.getObject(COSE_OKP_X_LABEL).getByteString(), keyAlg);
    }
    publicKeyMap.checkForUnread();
    return publicKey;
}
Also used : PublicKey(java.security.PublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) GeneralSecurityException(java.security.GeneralSecurityException) KeyTypes(org.webpki.crypto.KeyTypes) KeyAlgorithms(org.webpki.crypto.KeyAlgorithms) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) ECPoint(java.security.spec.ECPoint) ECPoint(java.security.spec.ECPoint) ECPublicKeySpec(java.security.spec.ECPublicKeySpec)

Example 5 with KeyAlgorithms

use of org.webpki.crypto.KeyAlgorithms in project openkeystore by cyberphone.

the class PEMDecoder method ecPublicKeyFromPKCS8.

// No instantiation please
static PublicKey ecPublicKeyFromPKCS8(byte[] pkcs8) throws IOException, GeneralSecurityException {
    ASN1Sequence seq = ParseUtil.sequence(DerDecoder.decode(pkcs8), 3);
    String oid = ParseUtil.oid(ParseUtil.sequence(seq.get(1), 2).get(1)).oid();
    seq = ParseUtil.sequence(DerDecoder.decode(ParseUtil.octet(seq.get(2))));
    byte[] publicKey;
    try {
        publicKey = ParseUtil.bitstring(ParseUtil.singleContext(seq.get(seq.size() - 1), 1));
    } catch (Exception e) {
        throw new GeneralSecurityException("This implementation requires PKCS8 with public key attribute");
    }
    int length = (publicKey.length - 1) / 2;
    byte[] parm = new byte[length];
    System.arraycopy(publicKey, 1, parm, 0, length);
    BigInteger x = new BigInteger(1, parm);
    System.arraycopy(publicKey, 1 + length, parm, 0, length);
    BigInteger y = new BigInteger(1, parm);
    for (KeyAlgorithms ka : KeyAlgorithms.values()) {
        if (oid.equals(ka.getECDomainOID())) {
            if (oid.equals(ka.getECDomainOID())) {
                ECPoint w = new ECPoint(x, y);
                return KeyFactory.getInstance("EC").generatePublic(new ECPublicKeySpec(w, ka.getECParameterSpec()));
            }
        }
    }
    throw new IOException("Failed creating EC public key from private key");
}
Also used : ASN1Sequence(org.webpki.asn1.ASN1Sequence) GeneralSecurityException(java.security.GeneralSecurityException) BigInteger(java.math.BigInteger) KeyAlgorithms(org.webpki.crypto.KeyAlgorithms) IOException(java.io.IOException) ECPoint(java.security.spec.ECPoint) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) ECPoint(java.security.spec.ECPoint) ECPublicKeySpec(java.security.spec.ECPublicKeySpec)

Aggregations

KeyAlgorithms (org.webpki.crypto.KeyAlgorithms)20 IOException (java.io.IOException)7 GeneralSecurityException (java.security.GeneralSecurityException)7 ECPoint (java.security.spec.ECPoint)6 KeyPair (java.security.KeyPair)5 KeyPairGenerator (java.security.KeyPairGenerator)4 PublicKey (java.security.PublicKey)4 ECPublicKey (java.security.interfaces.ECPublicKey)4 RSAPublicKey (java.security.interfaces.RSAPublicKey)4 ECPublicKeySpec (java.security.spec.ECPublicKeySpec)4 Test (org.junit.Test)4 BigInteger (java.math.BigInteger)3 PrivateKey (java.security.PrivateKey)3 ASN1Sequence (org.webpki.asn1.ASN1Sequence)3 ECKey (java.security.interfaces.ECKey)2 ECPrivateKey (java.security.interfaces.ECPrivateKey)2 RSAKey (java.security.interfaces.RSAKey)2 ECGenParameterSpec (java.security.spec.ECGenParameterSpec)2 ECPrivateKeySpec (java.security.spec.ECPrivateKeySpec)2 RSAKeyGenParameterSpec (java.security.spec.RSAKeyGenParameterSpec)2