Search in sources :

Example 6 with Command

use of org.nhindirect.common.tooling.Command in project nhin-d by DirectProject.

the class PKCS11Commands method updateKeyPairCert.

@Command(name = "UpdateKeyPairCert", usage = UPDATE_PUB_KEY_CERT)
public void updateKeyPairCert(String[] args) {
    final String certFileName = StringArrayUtil.getRequiredValue(args, 0);
    final String keyName = StringArrayUtil.getRequiredValue(args, 1);
    final File certFile = new File(certFileName);
    if (!certFile.exists()) {
        System.out.println("Certificate file " + certFile.getAbsolutePath() + " could not be found.");
        return;
    }
    try {
        final KeyStore ks = mgr.getKS();
        if (!ks.containsAlias(keyName)) {
            System.out.println("Entry with key name " + keyName + " does not exist.");
            return;
        }
        final X509Certificate storedCert = (X509Certificate) ks.getCertificate(keyName);
        if (storedCert == null) {
            System.out.println("Key name " + keyName + " does not contain a certificate that can be updated.  This key may not be an RSA key pair.");
            return;
        }
        // import the certificate
        final X509Certificate importCert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(FileUtils.openInputStream(certFile));
        // make sure the public keys match... the is necessary because the private key associated with the public key must be a valid key pair
        if (!importCert.getPublicKey().equals(storedCert.getPublicKey())) {
            System.out.println("Imported public key does not match the stored public key");
            return;
        }
        // update the public key
        final PrivateKey privKey = (PrivateKey) ks.getKey(keyName, "".toCharArray());
        ks.setKeyEntry(keyName, privKey, "".toCharArray(), new X509Certificate[] { importCert });
        System.out.println("Certificate updated.");
    } catch (Exception e) {
        System.err.println("Failed to update certificate: " + e.getMessage());
    }
}
Also used : PrivateKey(java.security.PrivateKey) File(java.io.File) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Command(org.nhindirect.common.tooling.Command)

Example 7 with Command

use of org.nhindirect.common.tooling.Command in project nhin-d by DirectProject.

the class PKCS11Commands method addUserSecretKey.

@Command(name = "CreateUserSecretKey", usage = ADD_USER_SECRET_KEY)
public void addUserSecretKey(String[] args) {
    final String keyName = StringArrayUtil.getRequiredValue(args, 0);
    final String keyText = StringArrayUtil.getRequiredValue(args, 1);
    try {
        byte[] key = keyText.getBytes("UTF-8");
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        key = sha.digest(key);
        // use only first 128 bitc
        key = Arrays.copyOf(key, 16);
        mgr.clearKey(keyName);
        mgr.setKey(keyName, new SecretKeySpec(key, "AES"));
    } catch (Exception e) {
        System.err.println("Failed to add new random secret key: " + e.getMessage());
        e.printStackTrace();
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) MessageDigest(java.security.MessageDigest) Command(org.nhindirect.common.tooling.Command)

Example 8 with Command

use of org.nhindirect.common.tooling.Command in project nhin-d by DirectProject.

the class PKCS11Commands method exportPublicKey.

@Command(name = "ExportPublicKey", usage = EXPORT_PUBLIC_KEY)
public void exportPublicKey(String[] args) {
    final String alias = StringArrayUtil.getRequiredValue(args, 0);
    final String file = StringArrayUtil.getOptionalValue(args, 1, alias + "-publicKey.der");
    try {
        final KeyStore ks = mgr.getKS();
        if (!ks.containsAlias(alias)) {
            System.out.println("Entry with key name " + alias + " does not exist.");
            return;
        }
        final X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
        if (cert == null) {
            System.out.println("Key name " + alias + " does not contain a public key");
            return;
        }
        final File fl = new File(file);
        FileUtils.writeByteArrayToFile(fl, cert.getPublicKey().getEncoded());
        System.out.println("Public key written to file " + fl.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to export public key: " + e.getMessage());
    }
}
Also used : KeyStore(java.security.KeyStore) File(java.io.File) X509Certificate(java.security.cert.X509Certificate) Command(org.nhindirect.common.tooling.Command)

Example 9 with Command

use of org.nhindirect.common.tooling.Command in project nhin-d by DirectProject.

the class PKCS11Commands method testSignatureSpeed.

@Command(name = "TestSignatureSpeed", usage = MESSAGE_SIGN_PROFILING)
public void testSignatureSpeed(String[] args) {
    final String alias = StringArrayUtil.getRequiredValue(args, 0);
    final int numSigs = Integer.parseInt(StringArrayUtil.getRequiredValue(args, 1));
    int numThreads = Integer.parseInt(StringArrayUtil.getOptionalValue(args, 2, "1"));
    if (numThreads < 1) {
        System.out.println("Number of threads cannot be less than 1.  Setting number of threads to 1");
        numThreads = 1;
    } else if (numThreads > 20) {
        System.out.println("Number of thread cannot be greater than 20.  Setting number of threads to 20");
        numThreads = 20;
    }
    try {
        final KeyStore ks = mgr.getKS();
        final PrivateKey privKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
        if (privKey == null) {
            System.out.println("Key name " + alias + " does not contain a private key");
            return;
        }
        // create some random bytes
        byte[] b = new byte[2048];
        new Random().nextBytes(b);
        // generate a SHA256 hash
        MessageDigest dig = MessageDigest.getInstance("SHA256", "BC");
        dig.update(b);
        byte[] digest = dig.digest();
        // now perform the operations
        final SigTestThread[] sigThreads = new SigTestThread[numThreads];
        final Thread[] thrds = new Thread[numThreads];
        long startTime = System.currentTimeMillis();
        for (int idx = 0; idx < numThreads; ++idx) {
            sigThreads[idx] = new SigTestThread(numSigs, digest, privKey, ks.getProvider());
            thrds[idx] = new Thread(sigThreads[idx]);
            thrds[idx].setDaemon(true);
            thrds[idx].setName("SigThread" + idx);
            thrds[idx].start();
        }
        // wait for each thread to die
        for (int idx = 0; idx < numThreads; ++idx) thrds[idx].join();
        long totalTime = System.currentTimeMillis() - startTime;
        int totalNumSigs = numSigs * numThreads;
        // get seconds
        int secs = (int) totalTime / 1000;
        int averageSpeed = totalNumSigs / secs;
        System.out.println("\r\nTotal runtime: " + totalTime + "ms.");
        System.out.println("\r\nNumber of signatures: " + totalNumSigs);
        System.out.println("Average speed: " + averageSpeed + " signatures per second.");
    } catch (Exception e) {
        System.err.println("Failed to test key signatures: " + e.getMessage());
    }
}
Also used : PrivateKey(java.security.PrivateKey) KeyStore(java.security.KeyStore) Random(java.util.Random) SecureRandom(java.security.SecureRandom) MessageDigest(java.security.MessageDigest) Command(org.nhindirect.common.tooling.Command)

Example 10 with Command

use of org.nhindirect.common.tooling.Command in project nhin-d by DirectProject.

the class PKCS11Commands method createCSR.

@Command(name = "CreateCSR", usage = CREATE_CSR)
public void createCSR(String[] args) {
    final String alias = StringArrayUtil.getRequiredValue(args, 0);
    final String commonName = StringArrayUtil.getRequiredValue(args, 1);
    final String subjectAltName = StringArrayUtil.getRequiredValue(args, 2);
    final String keyUsage = StringArrayUtil.getRequiredValue(args, 3);
    // make sure we have a valid keyUsage
    if (!(keyUsage.compareToIgnoreCase("DigitalSignature") == 0 || keyUsage.compareToIgnoreCase("KeyEncipherment") == 0 || keyUsage.compareToIgnoreCase("DualUse") == 0)) {
        System.out.println("Invalid key usage.");
        return;
    }
    final Vector<String> additionalRDNFields = new Vector<String>();
    int cnt = 4;
    String rdnField;
    do {
        rdnField = StringArrayUtil.getOptionalValue(args, cnt++, "");
        if (!StringUtils.isEmpty(rdnField))
            additionalRDNFields.add(rdnField);
    } while (!StringUtils.isEmpty(rdnField));
    try {
        final KeyStore ks = mgr.getKS();
        if (!ks.containsAlias(alias)) {
            System.out.println("Entry with key name " + alias + " does not exist.");
            return;
        }
        final X509Certificate storedCert = (X509Certificate) ks.getCertificate(alias);
        if (storedCert == null) {
            System.out.println("Key name " + alias + " does not contain a certificate that can be exported.  This key may not be an RSA key pair.");
            return;
        }
        final PrivateKey privKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
        if (privKey == null) {
            System.out.println("Failed to object private key.  This key may not be an RSA key pair.");
            return;
        }
        // create the CSR
        //  create the extensions that we want
        final X509ExtensionsGenerator extsGen = new X509ExtensionsGenerator();
        // Key Usage
        int usage;
        if (keyUsage.compareToIgnoreCase("KeyEncipherment") == 0)
            usage = KeyUsage.keyEncipherment;
        else if (keyUsage.compareToIgnoreCase("DigitalSignature") == 0)
            usage = KeyUsage.digitalSignature;
        else
            usage = KeyUsage.keyEncipherment | KeyUsage.digitalSignature;
        extsGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(usage));
        // Subject Alt Name
        int nameType = subjectAltName.contains("@") ? GeneralName.rfc822Name : GeneralName.dNSName;
        final GeneralNames altName = new GeneralNames(new GeneralName(nameType, subjectAltName));
        extsGen.addExtension(X509Extensions.SubjectAlternativeName, false, altName);
        // Extended Key Usage
        final Vector<KeyPurposeId> purposes = new Vector<KeyPurposeId>();
        purposes.add(KeyPurposeId.id_kp_emailProtection);
        extsGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(purposes));
        // Basic constraint
        final BasicConstraints bc = new BasicConstraints(false);
        extsGen.addExtension(X509Extensions.BasicConstraints, true, bc);
        // create the extension requests
        final X509Extensions exts = extsGen.generate();
        final ASN1EncodableVector attributes = new ASN1EncodableVector();
        final Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(exts.toASN1Object()));
        attributes.add(attribute);
        final DERSet requestedAttributes = new DERSet(attributes);
        // create the DN
        final StringBuilder dnBuilder = new StringBuilder("CN=").append(commonName);
        for (String field : additionalRDNFields) dnBuilder.append(",").append(field);
        final X500Principal subjectPrin = new X500Principal(dnBuilder.toString());
        final X509Principal xName = new X509Principal(true, subjectPrin.getName());
        // create the CSR
        final PKCS10CertificationRequest request = new PKCS10CertificationRequest("SHA256WITHRSA", xName, storedCert.getPublicKey(), requestedAttributes, privKey, ks.getProvider().getName());
        final byte[] encodedCSR = request.getEncoded();
        final String csrString = "-----BEGIN CERTIFICATE REQUEST-----\r\n" + Base64.encodeBase64String(encodedCSR) + "-----END CERTIFICATE REQUEST-----";
        final File csrFile = new File(alias + "-CSR.pem");
        FileUtils.writeStringToFile(csrFile, csrString);
        System.out.println("CSR written to " + csrFile.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to create CSR : " + e.getMessage());
    }
}
Also used : PrivateKey(java.security.PrivateKey) Attribute(org.bouncycastle.asn1.x509.Attribute) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) DERSet(org.bouncycastle.asn1.DERSet) X509Principal(org.bouncycastle.jce.X509Principal) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) X509ExtensionsGenerator(org.bouncycastle.asn1.x509.X509ExtensionsGenerator) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) PKCS10CertificationRequest(org.bouncycastle.jce.PKCS10CertificationRequest) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X500Principal(javax.security.auth.x500.X500Principal) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) File(java.io.File) Command(org.nhindirect.common.tooling.Command)

Aggregations

Command (org.nhindirect.common.tooling.Command)11 KeyStore (java.security.KeyStore)8 File (java.io.File)6 PrivateKey (java.security.PrivateKey)6 X509Certificate (java.security.cert.X509Certificate)5 SecretKey (javax.crypto.SecretKey)4 Key (java.security.Key)3 MessageDigest (java.security.MessageDigest)2 Cipher (javax.crypto.Cipher)2 IvParameterSpec (javax.crypto.spec.IvParameterSpec)2 X509Principal (org.bouncycastle.jce.X509Principal)2 AlgorithmParameters (java.security.AlgorithmParameters)1 KeyPair (java.security.KeyPair)1 KeyPairGenerator (java.security.KeyPairGenerator)1 SecureRandom (java.security.SecureRandom)1 ArrayList (java.util.ArrayList)1 Calendar (java.util.Calendar)1 Random (java.util.Random)1 Vector (java.util.Vector)1 KeyGenerator (javax.crypto.KeyGenerator)1