CKR_USER_NOT_LOGGED_IN when generating key pair using sunPKCS11 provider - pkcs#11

When trying to generate rsa key pair with sun PKCS11 provider, method generateKeyPair() throws ProviderException: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_USER_NOT_LOGGED_IN
My code looks like this:
Provider prov = ... // initialize provider
KeyStore ks = KeyStore.getInstance("PKCS11", prov);
ks.load(null, "pass".toCharArray());
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", prov);
keyGen.initialize(2048);
KeyPair kp = keyGen.generateKeyPair(); // exception thrown here
I tried using AuthProvider right after provider initialization like so:
AuthProvider aprov = (AuthProvider) prov;
aprov.login(null, callbacks -> {
log.error("### Inside callbacks {}", callbacks.length);
});
aprov.setCallbackHandler(callbacks -> {
log.error("### Inside setCallBackHandler {}", callbacks.length);
});
But I don't see any logging output, so that means lambdas are not executed.
The ultimate goal is to generate RSA key pair and store it in keystore (HSM) via PKCS11.
I tried openjdk 8 and oracle jdk 8. Also when listing aliases from keystore, I get an empty list, but I know there is one entry. Adding -Djava.security.debug=sunpkcs11 changed nothing.

The problem in my case was wrong slot number in provider configuration. The selected slot was labeled as "accelerator" which does not support the creation of "private objects" - from HSM documentation.
After switching to a different slot, key generation and storage into keystore works.

Related

Bukkit - Why is it displaying null (using a config file)

So, I am making a custom plugin for my server, and one of my features requires me to set an integer in a gui that shows how many 'CommonPackages' a user has. The issue that I am having is that when I am getting the String from my config (My config uses a custom file creation/management class that was given to me by a friend) it is saying that it is null in the gui, I do not get any errors in the console, please may someone help me? The item in the gui and the code for setting the item in the gui.
Item in the gui
gui creation code:
public static Inventory WhiteBackpack(Player player) {
UUID uuid = player.getUniqueId();
Inventory inv = Bukkit.createInventory(null, 27, (inventoryname));
ItemStack common = new ItemStack(Material.INK_SACK);
common.setDurability((byte) 8);
ItemMeta commonMeta = common.getItemMeta();
commonMeta.setDisplayName(Utils.chat("&fCommon Packages &8» &f&l" + Main.pl.getFileControl().getConfig().getString("players." + uuid + ".Packages.Common"))); //How I access my custom configs.
common.setItemMeta(commonMeta);
inv.setItem(10, common);
return inv;
}
Without the code of your method to get the config I can only say that the string in the actual file is not present.
As the Bukkit documentation states:
If the String does not exist and no default value was specified, this will return null.
So either the key just does not exist in the file or you pointed to the wrong file. The configuration should be well formated, too. (no tabs, only spaces)

servicestack.redis getvalues gives junk values

I am facing an issue getting junk values like 'OK' or '0' or some 'numeric' values while reading values from Redis. This happens while reading normal key and hash keys as well. We have upgraded all the service stack components and still facing the issues. Please find the component details and the code snippet in c#
Our environment: We have setup sentinel, and each sentinel is paired with a Redis instance. Now we have setup three instances of sentinel and three instances of redis server. We were using read only client for reading values and read-write client for writing values to Redis. Even after using read-write client for reading and writing is also giving the same junk value problems.
Components:
ServiceStack.Common v 5.1.0.0
ServiceStack.Redis v 5.1.0.0
ServiceStack.Interfaces v 5.1.0.0
ServiceStack.Text v 5.1.0.0
Redis server v 3.0.503
OS: Windows server 2012 R2
code snippet:
private static IredisClientManager m_redisManager;
initializeRedis()
{
if(m_redisManager == null)
{
var sentinel = new RedisSentinel(
"193.168.1.1:16380,193.168.1.2:16380,193.168.1.3:16380"
,"testmaster")
{
RefreshSentinelHostsAfter = 10;
};
sentinel.RedisManagerFactory += (master,slaves)
=> new RedisManagerPool(master);
m_redisManager = sentinel.Start();
}
}
public string GetValue(string key)
{
string val;
using(var client = m_redisManager.GetClient())
{
val = client.GetValue(key);
}
return val;
}
Note:
1. m_redisManager is declared as static, so that it runs only once. Each call will share this manager
2. client is disposing after each call to get value
3. My application is a multi threaded, so reading from multiple thread may happen at the same time. And application is muti instancing from same machine and difeerent machine as well.
4. The above code is from component which interact with Redis.
5. Client will call GetValue function
What could be the problem? Can someone help

Setting up and accessing Flink Queryable State (NullPointerException)

I am using Flink v1.4.0 and I have set up two distinct jobs. The first is a pipeline that consumes data from a Kafka Topic and stores them into a Queryable State (QS). Data are keyed by date. The second submits a query to the QS job and processes the returned data.
Both jobs were working fine with Flink v.1.3.2. But with the new update, everything has broken. Here is part of the code for the first job:
private void runPipeline() throws Exception {
StreamExecutionEnvironment env = configurationEnvironment();
QueryableStateStream<String, DataBucket> dataByDate = env.addSource(sourceDataFromKafka())
.map(NewDataClass::new)
.keyBy(data.date)
.asQueryableState("QSName", reduceIntoSingleDataBucket());
}
and here is the code on client side:
QueryableStateClient client = new QueryableStateClient("localhost", 6123);
// the state descriptor of the state to be fetched.
ValueStateDescriptor<DataBucket> descriptor = new ValueStateDescriptor<>(
"QSName",
TypeInformation.of(new TypeHint<DataBucket>() {}));
jobId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
String key = "2017-01-06";
CompletableFuture<ValueState<DataBucket> resultFuture = client.getKvState(
jobId,
"QSName",
key,
BasicTypeInfo.STRING_TYPE_INFO,
descriptor);
try {
ValueState<DataBucket> valueState = resultFuture.get();
DataBucket bucket = valueState.value();
System.out.println(bucket.getLabel());
} catch (IOException | InterruptionException | ExecutionException e) {
throw new RunTimeException("Unable to query bucket key: " + key , e);
}
I have followed the instructions as per the following link:
https://ci.apache.org/projects/flink/flink-docs-release-1.4/dev/stream/state/queryable_state.html
making sure to enable the queryable state on my Flink cluster by including the flink-queryable-state-runtime_2.11-1.4.0.jar from the opt/ folder of your Flink distribution to the lib/ folder and checked it runs in the task manager.
I keep getting the following error:
Exception in thread "main" java.lang.NullPointerException
at org.apache.flink.api.java.typeutils.GenericTypeInfo.createSerializer(GenericTypeInfo.java:84)
at org.apache.flink.api.common.state.StateDescriptor.initializeSerializerUnlessSet(StateDescriptor.java:253)
at org.apache.flink.queryablestate.client.QueryableStateClient.getKvState(QueryableStateClient.java:210)
at org.apache.flink.queryablestate.client.QueryableStateClient.getKvState(QueryableStateClient.java:174)
at com.company.dept.query.QuerySubmitter.main(QuerySubmitter.java:37)
Any idea of what is happening? I think that my requests don't reach the QS at all ... Really don't know if and how I should change anything. Thanks.
So, as it turned out, it was 2 things that were causing this error. The first was the use of the wrong constructor for creating a descriptor on the client side. Rather than using the one that only takes as input a name for the QS and a TypeHint, I had to use another one where a keySerialiser along with a default value are provided as per below:
ValueStateDescriptor<DataBucket> descriptor = new ValueStateDescriptor<>(
"QSName",
TypeInformation.of(new TypeHint<DataBucket>() {}).createSerializer(new ExecutionConfig()),
DataBucket.emptyBucket()); // or anything that can be used as a default value
The second was relevant to the host and port values. The port was different from v1.3.2 now set to 9069 and the localhost was also different in my case. You can verify both by checking the logs of any task manager for the line:
Started the Queryable State Proxy Server # ....
Finally, in case you are here because you are looking to allow port-range for queryable state client proxy, I suggest you follow the respective issue (FLINK-7788) here: https://issues.apache.org/jira/browse/FLINK-7788.

Attempted to read or write protected memory. PKCS11Interop

I am getting Access violation exception in the highlighed line.
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I have the certificate on the hsm and the label . I am building my application as x64
public void getCertificateFromHSM(string certLabel) {
List<ObjectAttribute> objectAttributes = new List<ObjectAttribute>();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, certLabel));
**session.FindObjectsInit(objectAttributes);** --Exception from here
// Get search results
List<ObjectHandle> foundObjects = session.FindObjects(2);
// Terminate searching
session.FindObjectsFinal();
// Prepare list of empty attributes we want to read
List<CKA> attributes = new List<CKA>();
attributes.Add(CKA.CKA_LABEL);
attributes.Add(CKA.CKA_VALUE);
}
I am getting exception from this line session.FindObjectsInit();. I am new to pkcs11.
Any help in this regard is appreciated.
I also tried to build the application as 32 bit by passing the 32bit crypto.dll ,but in that case i am getting exception from this line in PKCS11Interop Net.Pkcs11Interop.LowLevelAPI81.Delegates.InitializeWithGetF‌​unctionList(IntPtr libraryHandle) and the exception is
Value was either too large or too small for a UInt32. OverflowExcepiton was unhandled.
You seem to be using wrong set of HighLevelAPIs. You need to use classes from Net.Pkcs11Interop.HighLevelAPI namespace without any numbers at the end.
In other words you need to use following line
using Net.Pkcs11Interop.HighLevelAPI;
in your code instead of
using Net.Pkcs11Interop.HighLevelAPI81;
See Pkcs11Interop library architecture for more info and you can also take a look at official code samples which are using Net.Pkcs11Interop.HighLevelAPI too.

how to load an rsa asymmetric key pair with obj-c on the iphone?

I have the raw bytes of public and private key in a buffer and want to use that information to encrypt / decrypt data.
I do know that I could generate a keypair using SecKeyGeneratePair and then save it to the keychain, but i don't want that...
essentially, i need the Objective-C equivalent of the following Java Code (using Bouncycastle)
BigInteger modulus = ....
BigInteger publicExponent = ....
BigInteger privateExponent = ....
RSAKeyParameters pubKey = new RSAKeyParameters(false, modulus, publicExponent);
RSAKeyParameters privKey = new RSAKeyParameters(true, modulus, privateExponent);
return new AsymmetricCipherKeyPair(pubKey, privKey);
Any ideas? I'm really stuck on that problem....
Well, I know that OpenSSL allows you to do this, so you might want to investigate compiling OpenSSL into your project...
This link looks like it has decent instructions on how to do that.