Java API
HSM Dinamo
Loading...
Looking for...
No entries found
GenSessionKeyFromEcdhKey.java

Example of generating a session key from elliptical keys (ECDH).

See Note on examples.
package doxy.examples;
import java.util.Arrays;
import com.dinamonetworks.Dinamo;
import br.com.trueaccess.TacException;
import br.com.trueaccess.TacNDJavaLib;
public class GenSessionKeyFromEcdhKey {
private static String strAddr = "127.0.0.1";
private static String strUsrId = "master";
private static String strPwd = "12345678";
private static String strLocalKey = "test_local_key";
private static String strPeerKey = "test_peer_key";
private static String strSessionKey = "test_session_key";
public static void main(String[] args) {
Dinamo api = new Dinamo();
try {
System.out.println("--> Login HSM and create 2 Brainpool keys");
api.openSession(strAddr, strUsrId, strPwd);
api.createKey(strLocalKey, TacNDJavaLib.ALG_ECC_BRAINPOOL_P512T1);
api.createKey(strPeerKey, TacNDJavaLib.ALG_ECC_BRAINPOOL_P512T1);
System.out.println("--> Extract public part from local key");
byte[] pbPeerPubKey = api.exportKey(strPeerKey, TacNDJavaLib.PUBLICKEY_BLOB);
System.out.println("--> Construct a session key");
byte[] pbSharedSecret = api.genEcdhKey( TacNDJavaLib.DN_GEN_KEY_KDF_RAW_SECRET,
strLocalKey,
pbPeerPubKey );
/*
* The shared secret is used directly in this example, only for educational purposes!!
* We strongly advise to use KDF(Key Derivation Function) before importing the key.
* */
api.importKey( strSessionKey,
TacNDJavaLib.PLAINTEXTKEY_BLOB,
TacNDJavaLib.ALG_AES_256,
TacNDJavaLib.EXPORTABLE_KEY,
pbSharedSecret,
TacNDJavaLib.ALG_AES_256_LEN);
System.out.println("--> Encrypt data with test buffer");
byte[] pbClearBuffer = "askdfkasdfaksdfa".getBytes();
byte[] pbEncryptedBuffer = api.encrypt(strSessionKey, pbClearBuffer);
byte[] pbDecryptedBuffer = api.decrypt(strSessionKey, pbEncryptedBuffer);
System.out.println("--> Test operation");
if(!Arrays.equals(pbClearBuffer, pbDecryptedBuffer))
{
System.out.println("Decrypted buffer and clear text buffer are different!");
}
System.out.println("--> Delete keys");
api.deleteKey(strLocalKey);
api.deleteKey(strPeerKey);
api.deleteKey(strSessionKey);
api.closeSession();
System.out.println("The process ended sucessfully");
} catch (TacException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}