Skip to content

Instantly share code, notes, and snippets.

@mechazod
Last active December 14, 2017 17:18
Show Gist options
  • Save mechazod/630292945c73e679a3fd72d264cdb1fb to your computer and use it in GitHub Desktop.
Save mechazod/630292945c73e679a3fd72d264cdb1fb to your computer and use it in GitHub Desktop.
var graphene = require("graphene-pk11");
var Module = graphene.Module;
var lib = "/opt/local/lib/softhsm/libsofthsm2.so";
var mod = Module.load(lib, "SoftHSM");
var SessionFlag = graphene.SessionFlag;
var UserType = graphene.UserType;
mod.initialize();
var slot = mod.getSlots(2);
if (slot.flags & graphene.SlotFlag.TOKEN_PRESENT) {
var session = slot.open(SessionFlag.SERIAL_SESSION | SessionFlag.RW_SESSION);
session.login("8888",UserType.USER);
// enc algorithm
var alg = {
name: "AES_CBC_PAD",
params: new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6]) // IV
};
// generate AES key
var key = session.generateKey(graphene.KeyGenMechanism.AES, {
"class": graphene.ObjectClass.SECRET_KEY,
"token": false,
"valueLen": 256 / 8,
"keyType": graphene.KeyType.AES,
"label": "My AES secret key",
"encrypt": true,
"decrypt": true
});
// decrypting
var enc = new Buffer("196edd82ecca5e7df08090edf2cb3322", "hex");
console.log("Enc:", enc); // Message: Encrypted message
var dec = session.createDecipher(alg, key).once(enc, new Buffer(enc.byteLength));
console.log("Message:", dec.toString()); // Message: decrypted message
session.logout();
session.close();
}
else {
console.error("Slot is not initialized");
}
mod.finalize();
@microshine
Copy link

You are generating new key. You cannot use such key for decryption. You need the same key which you used for encryption. You can use C_CreateObject or C_FindObject to get the same key

@mechazod
Copy link
Author

I don't have any idea how to do the finding object of encrypted. Can you give us help for that. Thanks in advance.

@mechazod
Copy link
Author

Do you have sample on how to get the session generated key and match it for decryption.

I found this physical object created on my machine when I set to token to true.

screen shot 2017-12-15 at 1 18 23 am

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment