How to cast "byte[] publicKey" to "Data Object" (to use ObjectHandle) - public-key-encryption

I'm extracting the Public key for encryption from the sender's Certificate as byte[] array
JObject o = JObject.Parse(reply);
string certResponse = o.GetValue("certificate").Value<string>();
byte[] certByteArray = Encoding.ASCII.GetBytes(certResponse);
//Extract Public key from Certificate
var certTest = new X509Certificate2(certByteArray);
var certPublicKey = certTest.GetPublicKey();
I wish to use PKCS11Interop Encrypt() function which takes ObjectHandle of the key to Encrypt message/data. The only way I find is to set ObjectAttributes and session.CreateObject(objectAttributes); and eventually DestroyObject.
However I get CKR_FUNCTION_NOT_SUPPORTED calling CreateObject(). As clarified by jariq in this post that OpenSC PKCS#11 library does not support/implement some functions defined in PKCS#11 specification, What is the alternative/workaround to use the byte array publicKey for encryption?

Related

Check if redis key is hash or string using restTemplate

I have Redis DB consisting of hashes and strings.
I got all keys from DB using this code:
Set<byte[]> keys = redisTemplate.getConnectionFactory().getConnection().keys("*".getBytes());
Iterator<byte[]> it = keys.iterator();
while(it.hasNext()){
byte[] data = (byte[])it.next();
String key = (new String(data, 0, data.length));
System.out.println(key);
}
from here: How to get all Keys from Redis using redis template
Since the key can be hash or string, how to determine when I can use opsForHash and opsForValue i.e. how to check if it is hash or it is a string in spring boot using restTemplate.
The Redis command to get the type of a key is TYPE: https://redis.io/commands/type
You can use RedisTemplate's public DataType type(K key) method to execute this: https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/RedisTemplate.html#type-K-
Here's an example:
Set<byte[]> keys = redisTemplate.getConnectionFactory().getConnection().keys("*".getBytes());
Iterator<byte[]> it = keys.iterator();
while(it.hasNext()){
byte[] data = (byte[])it.next();
String key = (new String(data, 0, data.length));
DataType type = redisTemplate.type(key);
if (type == DataType.HASH) {
// ...
} else if (type == DataType.STRING) {
// ...
}
}
Edit: one more piece of advice is that you may want to use SCAN instead of KEYS * (mentioned in one answer to the SO question you linked). Scan is generally better in production since it doesn't try to get and return all keys at once.

Spring Framework and encode/decode of public key

I am trying to create a new RsaVerifier to check a public key:
JwtHelper.decodeAndVerify(token, verifier);
I do believe it's a valid public key. I'm copying it correctly from my browser. It does begin with a return character though. It actually has them in several places:
-----BEGIN PUBLIC KEY-----\nMIIBI.....
It fails when creating an RsaVerifier.
SignatureVerifier verifier = null;
if (key.startsWith("-----BEGIN PUBLIC KEY-----")) {
logger.log("Trying to get key verifier...");
verifier = new RsaVerifier(key); //FAILS HERE
...
Specifically, it's failing on the last line in this snippet from RsaKeyHelper:
private static Pattern PEM_DATA = Pattern.compile("-----BEGIN (.*)-----(.*)-----END (.*)-----", Pattern.DOTALL);
static KeyPair parseKeyPair(String pemData) {
Matcher m = PEM_DATA.matcher(pemData.trim());
if (!m.matches()) {
throw new IllegalArgumentException("String is not PEM encoded data");
}
String type = m.group(1);
final byte[] content = b64Decode(utf8Encode(m.group(2))); //FAILS HERE
with error:
Exception validating token :
org.springframework.security.jwt.codec.InvalidBase64CharacterException: Bad
Base64 input character decimal 92 in array position 0
I know decimal 92 is a forward slash and I have one in position 0, in fact. However, I've tried removing the return characters and it doesn't recognize it as valid. Here's a link to the RsaKeyHelper class:
https://www.programcreek.com/java-api-examples/index.php?source_dir=spring-security-oauth-master/spring-security-jwt/src/main/java/org/springframework/security/jwt/crypto/sign/RsaKeyHelper.java
I am struggling to figure out how I can pass this key as a string that is accepted.

Spring ehcache - Not able to retrieve value based on custom key

I am using KeyGenerator to generate custom key while caching a component.
Here is the cacheable method:
#CachePut(value = "cacheOne", keyGenerator = "keyGenerator")
public CachedObject cacheMeta(final Object obj1,
final Object obj2,
final CachedObject cachedObject) {
return cachedObject;
}
Here is KeyGenerator implementation:
public Object generate(Object o, Method m ,Object ... params){
StringBuilder s=new StringBuilder();
return s.append(params[0].hashCode()).append(params[1].hashCode());
}
While retrieving value from cache, i am generating key as :
StringBuilder s= new StringBuilder();
s.append(obj1.hashCode().append(obj2.hashCode()));
Element elt=CacheManager.getInstance("cacheOne").get(s)
But it always returns null.
The problem is that you are using a StringBuilder as the cache key. StringBuilder has no equals or hashCode defined. So it relies on the ones defined on Object.
Which basically means that the get used to get the cache entry doesn't match the one putting the entry.
Using toString() to put
StringBuilder s = new StringBuilder();
return s.append(params[0].hashCode()).append(params[1].hashCode()).toString();
and get
StringBuilder s = new StringBuilder();
s.append("a".hashCode()).append("b".hashCode());
Cache.ValueWrapper wrapper = cache.get(s.toString());
solves it.
But I have to things to say.
First, using a StringBuilder here is useless because using String concatenation will let the compiler add a StringBuilder under the hood but be much nicer to read. So you could do
return params[0].hashCode() + "" + params[1].hashCode();
and
Cache.ValueWrapper wrapper = cache.get("a".hashCode() + "" + "b".hashCode());
which will work perfectly and have the same performance.
Then, relying on hashcodes to create a key is not safe. Hashcodes can have collisions. Even when appending two hashcodes. So you might mix entries on a given key.

Castle Core Invocation create a cache key from intercepted method

I'm using a interface interceptor to cache all methods that starts with "Get" but i can't figure out how to generate a unique cache key for every unknown parameter it can be anything and using GetHashCode is not an option as i can't be 100% sure that they have overridden the GetHashCode.
some thoughts was someting in the line of How can I create a unique hashcode for a JObject?
where JSON is used for a JObject i was thinking on JSON serialize every parameter then get the hash code like explained in the link above:
var obj = JToken.Parse(jsonString);
var comparer = new JTokenEqualityComparer();
var hashCode = comparer.GetHashCode(obj);
However i think this will be a performence hit so how can this be solved ?
The code i have so far is this but it wont handle the complex type situation where .ToString won't generate the raw value type like int, string etc.
private string CreateCacheKey(IInvocation invocation)
{
string className = invocation.TargetType.FullName;
string methodName = invocation.Method.Name;
var builder = new StringBuilder(100);
builder.Append(className);
builder.Append(".");
builder.Append(methodName);
for (int i = 0; i < invocation.Arguments.Length; i++)
{
var argument = invocation.Arguments[i];
var argumentValue = invocation.GetArgumentValue(i);
builder.Append("_");
builder.Append(argument);
if (argument != argumentValue)
{
builder.Append(argumentValue);
}
}
return string.Format("{0}-{1}", this.provider.CacheKey, builder);
}
I ended up using GetHashCode as it is the only viable solution if thay dont override the method it will not cache.

XmlReader.ReadContentAsObject always returns string type

According to the MSDN documentation, XMLWriter.WriteValue writes xsd type information to the xml for simple CLR types. Then XMLReader.ReadContentAsObject supposedly reads out the appropriately-typed object when the XML is parsed. However, this always seems to return a string object for me and the ValueType property of the XMLReader is string. I've tried inserting longs and DateTimes, but they always end up as strings. Any ideas what I'm doing wrong or is this a Windows Phone bug?
XML Writing Code
public void WriteXml(XmlWriter writer) {
// KeyValuePair<string, object> pair initialized previously
writer.WriteStartElement(pair.Key);
writer.WriteValue(pair.Value)
writer.WriteEndElement();
}
XML Parsing Code
public void ReadXml(XMLReader reader) {
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element) {
Type T = reader.ValueType; // T is string
reader.ReadStartElement();
object o = reader.ReadContentAsObject(); // o is string
o = reader.ReadContentAs(T, null); // o is string
}
}
}
You need to use a schema file (XSD) so that the framework can infer the type of a node. Otherwise ValueType will always return System.String.
MSDN says:
If a validation error occurs while parsing the content and the reader is an XmlReader object created by the Create method, the reader returns the content as a string. In other words when a validation error or warning occurs, the content is considered to be untyped.
I was making this too difficult. My goal was to serialize a Dictionary with generic type (string, object) by traversing its KeyValuePairs , but that class doesn't seem to be serializeable using XmlSerializer. I just created another class with two public properties, Key and Value, so I could use XmlSerializer. When deserializing with XmlSerializer, the type of Value is restored as long as it is a supported CLR type.
public void WriteXml(XmlWriter writer) {
// KeyValuePair<string, object> pair initialized previously
writer.WriteStartElement("entry");
MyClass toSerialize = new MyClass(pair.Key, pair.Value);
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
serializer.Serialize(writer, toSerialize);
writer.WriteEndElement();
}

Resources