Search in sources :

Example 1 with NAEParameterSpec

use of com.ingrian.security.nae.NAEParameterSpec in project CipherTrust_Application_Protection by thalescpl-io.

the class CustomLoggerSample method main.

public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        System.err.println("Usage: java CustomLoggerSample user password keyname");
        System.exit(-1);
    }
    String username = args[0];
    String password = args[1];
    String keyName = args[2];
    // add Ingrian provider to the list of JCE providers
    Security.addProvider(new IngrianProvider(new JavaUtilLogger()));
    // get the list of all registered JCE providers
    Provider[] providers = Security.getProviders();
    for (int i = 0; i < providers.length; i++) System.out.println(providers[i].getInfo());
    String dataToMac = "2D2D2D2D2D424547494E2050455253495354454E54204346EB17960";
    System.out.println("Data to mac \"" + dataToMac + "\"");
    NAESession session = null;
    try {
        // create HMAC key on the Key Manager
        // create NAE Session: pass in Key Manager user name and password
        session = NAESession.getSession(username, password.toCharArray());
        // create key which is exportable and deletable,
        // key owner is passed in Key Manager user.
        // For HmacSHA1 key length 160 bits
        // For HmacSHA256 key length is 256 bits
        // For HmacSHA384 key length is 384 bits
        // For HmacSHA512 key length is 512 bits
        NAEParameterSpec spec = new NAEParameterSpec(keyName, true, true, 160, session);
        KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1", "IngrianProvider");
        kg.init(spec);
        SecretKey secret_key = kg.generateKey();
        // get the handle to created key
        NAEKey key = NAEKey.getSecretKey(keyName, session);
        // create MAC instance to get the message authentication code
        Mac mac = Mac.getInstance("HmacSHA1", "IngrianProvider");
        mac.init(key);
        byte[] macValue = mac.doFinal(dataToMac.getBytes());
        // create MAC instance to verify the message authentication code
        Mac macV = Mac.getInstance("HmacSHA1Verify", "IngrianProvider");
        macV.init(key, new MACValue(macValue));
        byte[] result = macV.doFinal(dataToMac.getBytes());
        // check verification result
        if (result.length != 1 || result[0] != 1) {
            System.out.println("Invalid MAC.");
        } else {
            System.out.println("MAC Verified OK.");
        }
    } catch (Exception e) {
        System.out.println("The Cause is " + e.getMessage() + ".");
        throw e;
    } finally {
        if (session != null)
            session.closeSession();
    }
}
Also used : NAEParameterSpec(com.ingrian.security.nae.NAEParameterSpec) NAEKey(com.ingrian.security.nae.NAEKey) Mac(javax.crypto.Mac) IngrianProvider(com.ingrian.security.nae.IngrianProvider) IngrianProvider(com.ingrian.security.nae.IngrianProvider) Provider(java.security.Provider) MACValue(com.ingrian.security.nae.MACValue) SecretKey(javax.crypto.SecretKey) KeyGenerator(javax.crypto.KeyGenerator) NAESession(com.ingrian.security.nae.NAESession)

Example 2 with NAEParameterSpec

use of com.ingrian.security.nae.NAEParameterSpec in project CipherTrust_Application_Protection by thalescpl-io.

the class CryptoTool method doGenerate.

/**
 * Generates a key based on the input parameters.
 * @param keyName Key name to use
 * @param algName Algorith name to use
 * @param session NAESession
 * @param exportable Signifies whether the generated key is exportable
 * @param deletable Signifies whether the generate key is deletable
 * @param size Key size
 * @throws Exception
 * @return Returns whether the operation was successful
 */
private static boolean doGenerate(String keyName, String algName, NAESession session, boolean exportable, boolean deletable, int size) throws Exception {
    // error checking
    if (keyName == null) {
        System.err.println("Missing key name");
        return false;
    }
    if (algName == null) {
        System.err.println("Missing algorithm name");
        return false;
    }
    // Create key generator and use it to create the key
    if (!"RSA".equalsIgnoreCase(algName)) {
        KeyGenerator kg = KeyGenerator.getInstance(algName, "IngrianProvider");
        kg.init(new NAEParameterSpec(keyName, exportable, deletable, size, session));
        kg.generateKey();
    } else {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(algName, "IngrianProvider");
        kpg.initialize(new NAEParameterSpec(keyName, exportable, deletable, size, session));
        kpg.genKeyPair();
    }
    os.write("Key generated OK\n".getBytes());
    return true;
}
Also used : NAEParameterSpec(com.ingrian.security.nae.NAEParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator) KeyGenerator(javax.crypto.KeyGenerator)

Example 3 with NAEParameterSpec

use of com.ingrian.security.nae.NAEParameterSpec in project CipherTrust_Application_Protection by thalescpl-io.

the class KMIPCreateAndEncryptSample method main.

public static void main(String[] args) throws Exception {
    if (args.length != 5) {
        usage();
    }
    String keyName = args[4];
    int keyLength = 256;
    // add Ingrian provider to the list of JCE providers
    Security.addProvider(new IngrianProvider());
    KMIPSession kmipSession = null;
    NAESession naeSession = null;
    try {
        // create KMIP Session - specify client X.509 certificate and keystore password
        kmipSession = KMIPSession.getSession(new NAEClientCertificate(args[0], args[1].toCharArray()));
        // create key custom attributes
        NAEKey key;
        try {
            /* does the key exist? if so, delete it */
            /* get..Key method is merely a placeholder for a managed object 
                * with that name. */
            key = NAEKey.getSecretKey(keyName, kmipSession);
            /* getUID() will throw an exception if the key does not exist */
            if (key.getUID() != null) {
                System.out.println("Deleting key " + keyName + " with UID=" + key.getUID());
                key.delete();
            }
        } catch (NAEException missing) {
            if (missing.getMessage().equals("Key not found on server.")) {
                System.out.println("Key did not exist");
            } else
                throw missing;
        }
        /* create a secret key using KMIP JCE key generator */
        KMIPAttributes initialAttributes = new KMIPAttributes();
        initialAttributes.add(KMIPAttribute.CryptographicUsageMask, (int) (UsageMask.Encrypt.getValue() | UsageMask.Decrypt.getValue()));
        Calendar c = Calendar.getInstance();
        initialAttributes.addDate(KMIPAttribute.ActivationDate, c);
        NAEParameterSpec spec = new NAEParameterSpec(keyName, keyLength, (KMIPAttributes) initialAttributes, kmipSession);
        KeyGenerator kg = KeyGenerator.getInstance("AES", "IngrianProvider");
        kg.init(spec);
        SecretKey secretKey = kg.generateKey();
        System.out.println("Created key " + ((NAEKey) secretKey).getName());
        /* Once created, you may operate on the KMIP key. For example, 
             * add a KMIP group attribute to the KMIP - not required, just include 
             * as a sample of KMIP operations on the key */
        KMIPAttributes ka = new KMIPAttributes();
        ka.add(KMIPAttribute.ObjectGroup, 0, "group1");
        secretKey = NAEKey.getSecretKey(keyName);
        NAESecretKey sk = NAEKey.getSecretKey(keyName, kmipSession);
        sk.addKMIPAttributes(ka);
        /* Now use the NAEKey created for encryption using an NAESession
             * to a Key Manager server. Essentially this is the same code as the
             * SecretKeyEncryptionSample.java program
             * Nothing new is required to use the KMIP-created key on the 
             * Key Manager server.
             */
        // create NAE XML Session: pass in NAE user name and password
        naeSession = NAESession.getSession(args[2], args[3].toCharArray());
        // Get SecretKey (just a handle to it, key data does not leave the server
        // Note: KMIP keys objects need to be re-retrieved on the XML session
        key = NAEKey.getSecretKey(keyName, naeSession);
        // get IV
        NAESecureRandom rng = new NAESecureRandom(naeSession);
        byte[] iv = new byte[16];
        rng.nextBytes(iv);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        // get a cipher
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "IngrianProvider");
        // initialize cipher to encrypt.
        cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
        String dataToEncrypt = "2D2D2D2D2D424547494E2050455253495354454E54204346EB17960";
        System.out.println("Data to encrypt \"" + dataToEncrypt + "\"");
        // encrypt data
        byte[] outbuf = cipher.doFinal(dataToEncrypt.getBytes());
        // to decrypt data, initialize cipher to decrypt
        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
        // decrypt data
        byte[] newbuf = cipher.doFinal(outbuf);
        System.out.println("Decrypted data  \"" + new String(newbuf) + "\"");
    } catch (Exception e) {
        System.out.println("The Cause is " + e.getMessage() + ".");
        e.printStackTrace();
    } finally {
        if (kmipSession != null)
            kmipSession.closeSession();
        if (naeSession != null)
            naeSession.closeSession();
    }
}
Also used : NAEException(com.ingrian.security.nae.NAEException) KMIPAttributes(com.ingrian.security.nae.KMIPAttributes) NAEParameterSpec(com.ingrian.security.nae.NAEParameterSpec) NAEKey(com.ingrian.security.nae.NAEKey) NAESecureRandom(com.ingrian.security.nae.NAESecureRandom) Calendar(java.util.Calendar) NAESecretKey(com.ingrian.security.nae.NAESecretKey) NAEClientCertificate(com.ingrian.security.nae.NAEClientCertificate) NAEException(com.ingrian.security.nae.NAEException) IngrianProvider(com.ingrian.security.nae.IngrianProvider) KMIPSession(com.ingrian.security.nae.KMIPSession) SecretKey(javax.crypto.SecretKey) NAESecretKey(com.ingrian.security.nae.NAESecretKey) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) KeyGenerator(javax.crypto.KeyGenerator) NAESession(com.ingrian.security.nae.NAESession)

Example 4 with NAEParameterSpec

use of com.ingrian.security.nae.NAEParameterSpec in project CipherTrust_Application_Protection by thalescpl-io.

the class KMIPCertificateSample method main.

public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        usage();
    }
    // add Ingrian provider to the list of JCE providers
    Security.addProvider(new IngrianProvider());
    KMIPSession session = null;
    try {
        // create NAE Session: pass in Key Manager user name and password
        session = KMIPSession.getSession(new NAEClientCertificate(args[0], args[1].toCharArray()));
        // create certificate managed object ParameterSpec
        NAEParameterSpec spec = new NAEParameterSpec(args[2], 1024, (KMIPAttributes) null, session);
        // import the certificate
        byte[] c = Hex.decodeHex(certBytes.toCharArray());
        NAECertificate.importCertificate(c, null, spec);
        // query the certificate attributes via KMIP
        session.getUID(args[2]);
        Set<String> attrNames = session.listKMIPAttributes(args[2]);
        System.out.println("Attributes: " + attrNames);
        NAECertificate cert = new NAECertificate(args[2], session);
        KMIPAttributes getAttributes = new KMIPAttributes();
        getAttributes.add(KMIPAttribute.CertificateIdentifier);
        getAttributes.add(KMIPAttribute.ObjectType);
        getAttributes.add(KMIPAttribute.CertificateIssuer);
        getAttributes.add(KMIPAttribute.CertificateType);
        getAttributes.add(KMIPAttribute.CertificateSubject);
        KMIPAttributes gotAttributes = cert.getKMIPAttributes(getAttributes);
        KMIPCertificateIdentifier certIdentifier = gotAttributes.getCertificateIdentifier();
        KMIPCertificateSubject subject = gotAttributes.getCertificateSubject();
        KMIPCertificateTypes certType = gotAttributes.getCertificateType();
        KMIPCertificateIssuer issuer = gotAttributes.getCertificateIssuer();
        ObjectTypes ot = gotAttributes.getObjectType();
        if (ot != null) {
            System.out.println("Object Type KMIP Attribute: " + ot.getPrintName());
        } else {
            System.err.println("Object Type KMIP Attribute is null.");
        }
        if (certType != null) {
            System.out.println("Certificate Type KMIP Attribute: " + certType.getPrintName());
        } else {
            System.err.println("Certificate Type KMIP Attribute is null.");
        }
        if (certIdentifier == null) {
            System.err.println("Certificate Identifier KMIP Attribute is null.");
        } else {
            System.out.println("Certificate Identifier KMIP Attribute:");
            System.out.println("\tIssuer = " + certIdentifier.getIssuer());
            System.out.println("\tSerial Number" + certIdentifier.getSerialNumber());
        }
        if (issuer == null) {
            System.err.println("Certificate Issuer is null.");
        } else {
            System.out.println("Certificate Issuer:");
            System.out.println("\tIssuer Distinguished Name = " + issuer.getCertificateIssuerDistinguishedName());
            if (issuer.getCertificateIssuerAlternativeName() != null) {
                System.out.println("\tIssuer Alternative Name = " + issuer.getCertificateIssuerAlternativeName());
            }
        }
        if (subject == null) {
            System.err.println("Certificate Subject is null.");
        } else {
            System.out.println("Certificate Subject:");
            System.out.println("\tSubject Distinguished Name = " + subject.getCertificateSubjectDistinguishedName());
            if (subject.getCertificateSubjectAlternativeName() != null) {
                System.out.println("\tSubject Alternative Name = " + subject.getCertificateSubjectAlternativeName());
            }
        }
        // now export() a copy of the certificate back from the Key Manager
        byte[] exportedCert = cert.certificateExport();
        // compare the original and exported bytes
        if ((exportedCert != null) && Arrays.equals(Hex.decodeHex(certBytes.toCharArray()), exportedCert))
            System.out.println("Exported Certificate material equals original");
        else {
            System.out.println("Uh-oh!");
        }
        // print the bytes
        System.out.println("original: " + certBytes.toUpperCase());
        System.out.println("exported: " + TTLVUtil.toHexString(exportedCert));
        // delete the test cert and close the session
        cert.delete();
    } catch (Exception e) {
        System.out.println("The Cause is " + e.getMessage() + ".");
        e.printStackTrace();
    } finally {
        if (session != null)
            session.closeSession();
    }
}
Also used : NAEParameterSpec(com.ingrian.security.nae.NAEParameterSpec) KMIPAttributes(com.ingrian.security.nae.KMIPAttributes) KMIPCertificateIssuer(com.ingrian.security.nae.KMIPCertificateIssuer) NAECertificate(com.ingrian.security.nae.NAECertificate) KMIPCertificateIdentifier(com.ingrian.security.nae.KMIPCertificateIdentifier) KMIPCertificateTypes(com.ingrian.security.nae.KMIPCertificateTypes) ObjectTypes(com.ingrian.internal.kmip.api.ObjectType.ObjectTypes) NAEClientCertificate(com.ingrian.security.nae.NAEClientCertificate) IngrianProvider(com.ingrian.security.nae.IngrianProvider) KMIPSession(com.ingrian.security.nae.KMIPSession) KMIPCertificateSubject(com.ingrian.security.nae.KMIPCertificateSubject)

Example 5 with NAEParameterSpec

use of com.ingrian.security.nae.NAEParameterSpec in project CipherTrust_Application_Protection by thalescpl-io.

the class KMIPKeyPairSample method main.

public static void main(String[] args) {
    if (args.length != 4) {
        usage();
    }
    // add Ingrian provider to the list of JCE providers
    Security.addProvider(new IngrianProvider());
    String privateKeyName = args[2];
    String publicKeyName = args[3];
    KMIPSession session = null;
    try {
        // generate the public/private key pairs with client-side provider
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
        System.out.println("Provider: " + keyGen.getProvider().getName());
        keyGen.initialize(length);
        KeyPair generatedKeyPair = keyGen.generateKeyPair();
        // get the key material
        PrivateKey priv = generatedKeyPair.getPrivate();
        PublicKey pub = generatedKeyPair.getPublic();
        byte[] privKeyMaterial = priv.getEncoded();
        byte[] pubKeyMaterial = pub.getEncoded();
        // Register keys on the Key Manager
        // create NAE Session using a client certificate
        session = KMIPSession.getSession(new NAEClientCertificate(args[0], args[1].toCharArray()));
        // create a spec for the public key
        KMIPAttributes initialAttributes = new KMIPAttributes();
        initialAttributes.add(KMIPAttribute.CryptographicUsageMask, (int) (UsageMask.Verify.getValue()));
        NAEParameterSpec spec = new NAEParameterSpec(publicKeyName, length, (KMIPAttributes) initialAttributes, session);
        // create a public key - note: names must match
        NAEPublicKey naePub = NAEKey.getPublicKey(publicKeyName, session);
        // register the key
        String pubUID = naePub.registerKey(pubKeyMaterial, algorithm, keyFormat, spec);
        // print the Key Manager unique identifier for the key
        System.out.println("Created public key: " + pubUID);
        // do the same for the private key
        initialAttributes = new KMIPAttributes();
        initialAttributes.add(KMIPAttribute.CryptographicUsageMask, (int) (UsageMask.Sign.getValue()));
        spec = new NAEParameterSpec(privateKeyName, length, (KMIPAttributes) initialAttributes, session);
        NAEPrivateKey naePriv = NAEKey.getPrivateKey(privateKeyName, session);
        // remove PKCS#8 header from the key material
        byte[] truncatedKeyMaterial = new byte[privKeyMaterial.length - 26];
        System.arraycopy(privKeyMaterial, 26, truncatedKeyMaterial, 0, privKeyMaterial.length - 26);
        String privUID = naePriv.registerKey(truncatedKeyMaterial, algorithm, keyFormat, spec);
        System.out.println("Created private key: " + privUID);
        // Set the link attribute for the keys on the Key Manager
        naePriv.link(naePub);
        naePub.link(naePriv);
        System.out.println("Linked keys");
    } catch (Exception e) {
        System.out.println("The Cause is " + e.getMessage() + ".");
        e.printStackTrace();
    } finally {
        if (session != null)
            session.closeSession();
    }
}
Also used : KeyPair(java.security.KeyPair) KMIPAttributes(com.ingrian.security.nae.KMIPAttributes) NAEParameterSpec(com.ingrian.security.nae.NAEParameterSpec) PrivateKey(java.security.PrivateKey) NAEPrivateKey(com.ingrian.security.nae.NAEPrivateKey) NAEPrivateKey(com.ingrian.security.nae.NAEPrivateKey) PublicKey(java.security.PublicKey) NAEPublicKey(com.ingrian.security.nae.NAEPublicKey) NAEPublicKey(com.ingrian.security.nae.NAEPublicKey) KeyPairGenerator(java.security.KeyPairGenerator) NAEClientCertificate(com.ingrian.security.nae.NAEClientCertificate) IngrianProvider(com.ingrian.security.nae.IngrianProvider) KMIPSession(com.ingrian.security.nae.KMIPSession)

Aggregations

NAEParameterSpec (com.ingrian.security.nae.NAEParameterSpec)25 IngrianProvider (com.ingrian.security.nae.IngrianProvider)17 KeyGenerator (javax.crypto.KeyGenerator)12 NAESession (com.ingrian.security.nae.NAESession)11 KMIPSession (com.ingrian.security.nae.KMIPSession)10 NAEClientCertificate (com.ingrian.security.nae.NAEClientCertificate)10 NAEKey (com.ingrian.security.nae.NAEKey)10 KMIPAttributes (com.ingrian.security.nae.KMIPAttributes)9 SecretKey (javax.crypto.SecretKey)7 NAEPublicKey (com.ingrian.security.nae.NAEPublicKey)6 NAESecretKey (com.ingrian.security.nae.NAESecretKey)6 KeyPair (java.security.KeyPair)6 Provider (java.security.Provider)6 NAEPermission (com.ingrian.security.nae.NAEPermission)5 NAEPrivateKey (com.ingrian.security.nae.NAEPrivateKey)5 NAEException (com.ingrian.security.nae.NAEException)4 KeyPairGenerator (java.security.KeyPairGenerator)4 PrivateKey (java.security.PrivateKey)4 PublicKey (java.security.PublicKey)4 Cipher (javax.crypto.Cipher)4