How to get public key from private key stored in HSMs - hsm

I have some private keys stored in the HSM but without public keys. I want to get the corresponding public key using PKCS11 interface.
If the private key is a RSA key, I can extract the modulus from CKA_MODULUS and exponent from CKA_PUBLIC_EXPONENT, and then construct the public key with these two numbers.
However, when it comes to ECDSA(or DSA) keys, how can I achieve the same goal?
CKA_EC_POINT attribute is not available for private keys.
I think the only useful information I can get is its curve parameters from CKA_EC_PARAMS, which is not enough to get the public point.

If you're using PKCS#11 library that implements PKCS#11 specification v2.40 then CKA_PUBLIC_KEY_INFO attribute is what you are looking for.
If you're using PKCS#11 library that implements PKCS#11 specification older than 2.40 then you cannot read EC public key value from EC private key object unless your device vendor provides some vendor specific attribute similar to CKA_PUBLIC_KEY_INFO attribute.

Related

Override primary key generator strategy in Spring Boot when deployed to MySQL

In my application I want to support more databases to which it can be loaded, and for MS SQL Server I have set the identity generator to SEQUENCE
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
Because it can be deployed to MySQL as well, I need somehow to change the generator to IDENTITY since SEQUENCE is not available for MySQL, is there a way to do it programatically ?
The simplest solution would probably be to create your schema without the help of Hibernate (e.g. manage your schema using a tool like Liquibase) and use the DB capabilities for assigning the ids. In your specific scenario, you could probably use strategy = IDENTITY for both DBs (just so that Hibernate delegates the id column management to the DB) and then create an INSTEAD OF INSERT trigger for SQL Server. I'm not sure about performance, though.
If you still want Hibernate to do the job - it's not going to be super easy, but I can think of one option you could try:
Use the #GeneratedValue.name property with your id field:
#Id
#GeneratedValue(name = "my-entity-generator")
private Long id;
Declare two versions of my-entity-generator for the two databases. You need to put them on something that is optional for the entity scan. #GenericGenerator can be put on a package, for instance, so you can use two empty packages and declare the generators corresponding to the two strategies in their respective package-infos (never tried it with Spring, though, so I'm not sure if that will get picked up). You could probably also use two dummy #MappedSuperclasses in two different packages.
So, let's say you end up with one mapped superclass called com.example.mssql.Generators:
#MappedSuperclass
#GenericGenerator(name = "my-entity-generator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", ...)
public abstract class Generators {}
And another one called com.example.mysql.Generators:
#MappedSuperclass
#GenericGenerator(name = "my-entity-generator", strategy = "org.hibernate.id.IdentityGenerator")
public abstract class Generators {}
Conditionally include the two packages in the entity scan:
#Profile("mysql") // or #ConditionalOnProperty, or your own custom condition
#Configuration
#EntityScan(basePackages = "com.example.mysql")
public class MySqlConfig {}
#Profile("mssql") // or #ConditionalOnProperty, or your own custom condition
#Configuration
#EntityScan(basePackages = "com.example.mssql")
public class MsSqlConfig {}
(of course, for this to work, you need an unconditional #EntityScan on top of e.g. your application class that does not cover the two packages)
Another possible option could be to only have one generator declaration but instead use your own custom generator implementation that detects the DB and then delegates to either an IdentityGenerator or a SequenceStyleGenerator. Thus, you have one option that involves configuration magic and another that involves heavy coding.
(finally, I think you could also use Hibernate mapping XML files and - again - conditionally include them in your mapping, but it's an ancient technique and the documentation is not great)

JDO, org.json.simple.JSONObject and PostgreSQL JSON type

In my PostgreSQL database I have:
CREATE TABLE category (
// ...
category_name_localization JSON not null,
);
In Java, I have a JDO class like so:
#javax.jdo.annotations.PersistenceCapable(table = "category" )
public class Category extends _BlueEntity implements Serializable {
//...
private org.json.simple.JSONObject category_name_localization;
#javax.jdo.annotations.Column( name = "category_name_localization" )
public org.json.simple.JSONObject getCategoryNameLocalization() {
return category_name_localization;
}
}
When I use this class, DataNucleus gives the following exception:
org.datanucleus.exceptions.NucleusUserException: Field "com.advantagegroup.blue.ui.entity.Category.category_name_localization" is a map that has been specified without a join table and neither the key nor the value has a mapped-by specified. This is invalid!
at org.datanucleus.store.rdbms.RDBMSStoreManager.newJoinTable(RDBMSStoreManager.java:2720)
at org.datanucleus.store.rdbms.mapping.java.AbstractContainerMapping.initialize(AbstractContainerMapping.java:82)
at org.datanucleus.store.rdbms.mapping.MappingManagerImpl.getMapping(MappingManagerImpl.java:680)
at org.datanucleus.store.rdbms.table.ClassTable.manageMembers(ClassTable.java:518)
at org.datanucleus.store.rdbms.table.ClassTable.manageClass(ClassTable.java:424)
at org.datanucleus.store.rdbms.table.ClassTable.initializeForClass(ClassTable.java:1250)
at org.datanucleus.store.rdbms.table.ClassTable.initialize(ClassTable.java:271)
at org.datanucleus.store.rdbms.RDBMSStoreManager$ClassAdder.initializeClassTables(RDBMSStoreManager.java:3288)
at org.datanucleus.store.rdbms.RDBMSStoreManager$ClassAdder.run(RDBMSStoreManager.java:2897)
at org.datanucleus.store.rdbms.AbstractSchemaTransaction.execute(AbstractSchemaTransaction.java:118)
at org.datanucleus.store.rdbms.RDBMSStoreManager.manageClasses(RDBMSStoreManager.java:1637)
at org.datanucleus.store.rdbms.RDBMSStoreManager.getDatastoreClass(RDBMSStoreManager.java:665)
at org.datanucleus.store.rdbms.RDBMSStoreManager.getPropertiesForGenerator(RDBMSStoreManager.java:2098)
at org.datanucleus.store.AbstractStoreManager.getStrategyValue(AbstractStoreManager.java:1278)
at org.datanucleus.ExecutionContextImpl.newObjectId(ExecutionContextImpl.java:3668)
at org.datanucleus.state.StateManagerImpl.setIdentity(StateManagerImpl.java:2276)
at org.datanucleus.state.StateManagerImpl.initialiseForPersistentNew(StateManagerImpl.java:482)
at org.datanucleus.state.StateManagerImpl.initialiseForPersistentNew(StateManagerImpl.java:122)
at org.datanucleus.state.ObjectProviderFactoryImpl.newForPersistentNew(ObjectProviderFactoryImpl.java:218)
at org.datanucleus.ExecutionContextImpl.persistObjectInternal(ExecutionContextImpl.java:1986)
at org.datanucleus.ExecutionContextImpl.persistObjectWork(ExecutionContextImpl.java:1830)
at org.datanucleus.ExecutionContextImpl.persistObject(ExecutionContextImpl.java:1685)
at org.datanucleus.api.jdo.JDOPersistenceManager.jdoMakePersistent(JDOPersistenceManager.java:712)
at org.datanucleus.api.jdo.JDOPersistenceManager.makePersistent(JDOPersistenceManager.java:738)
at com.advantagegroup.blue.ui.jdo._BlueJdo.insert(_BlueJdo.java:40)
at ...
This error makes sense in a way, because org.json.simple.JSONObject extends Map. However, this field is not part of any relationships -- it is of type JSON and therefore it is natural to back it with JSONObject
How do I tell JDO / DataNucleus to chill and treat org.json.simple.JSONObject the same way it would a String or a Date?
Thanks!
DC
My understanding of this is that your default attempt is trying to persist a normal Map (since while it doesnt know what a JSONObject is, it does know what a Map is), and it will need a join table for that for RDBMS.
Since you presumably want the JSONObject persisted into a single column then you need to create a JDO AttributeConverter. I've done similar things with my own types and it works fine (i'm on v5.0.5 IIRC).
I also found this in their docs, for when you have your own Map class that it doesn't know how to handle by default in terms of replacing it with a proxy (to intercept the calls to put, putAll etc). If you add that line it will not try to wrap this field with a proxy (which it doesn't know how to do for that type, unless you tell it). If you wanted to auto-detect the JSONObject becoming "dirty" you would need to write a proxy wrapper, as per this page.
This doesn't answer how to map the column for that converter to use a "json" type in PostgreSQL, but i'd guess that if you set the sqlType you may get success in that respect.

computeRsaSha256Signature() returns Invalid argument: key error when key is public key or rsa private key

I need to sign a message using RSA-SHA256 and a public key in my Google Apps Script.
I am trying to use Utilities.computeRsaSha256Signature(value, key) for this, but I just get an Invalid argument: key error.
For the purpose of this question I have generated a key-pair like this:
openssl genrsa -out private.pem 32
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
My script looks like this:
function test() {
var privKey = "-----BEGIN RSA PRIVATE KEY-----\nMCwCAQACBQC6fs8xAgMBAAECBQCxyL35AgMA3ecCAwDXJwICKLcCAnF9AgIbnA==\n-----END RSA PRIVATE KEY-----\n";
var pubKey = "-----BEGIN PUBLIC KEY-----\nMCAwDQYJKoZIhvcNAQEBBQADDwAwDAIFALp+zzECAwEAAQ==\n-----END PUBLIC KEY-----\n";
Utilities.computeRsaSha256Signature("value", pubKey);
Utilities.computeRsaSha256Signature("value", privKey);
}
When I run this I get an Invalid argument: key error on the first call to computeRsaSha256Signature.
The error suggests there is something wrong with they key, but I can't figure out what the problem is. I've tried with both the public and the private key and I've tried to strip the newlines but everything fails with the same message.
My code looks very similar to the example in the documentation so I'm not sure what I am doing wrong.
How can Utilities.computeRsaSha256Signature() be used successfully?
Keys starting with BEGIN PRIVATE KEY have a different format than the ones with BEGIN RSA PRIVATE KEY.
I was starting from a key in the "RSA" format but the computeRsaSha256Signature needs a key in the non-RSA format.
You can convert from the latter to the former with:
openssl pkcs8 -topk8 -inform pem -in private.pem -outform pem -nocrypt -out newPrivate.pem
Source:
https://plus.google.com/106009755685055488206/posts/bYuPM6MGwsU
There are at least three different types of keys that can be used when doing a rsa sha256 signature:
BEGIN PRIVATE KEY
BEGIN RSA PRIVATE KEY
BEGIN PUBLIC KEY
As indicated by the accepted answer and based on my own testing it seems like computeRsaSha256Signature only supports the BEGIN PRIVATE KEY type.
As the accepted answer explains it is possible to convert a RSA PRIVATE KEY to a PRIVATE KEY however when all you have is the public key it's more complicated.
In this scenario an external library like JSEncrypt can be useful. However this assumes that the window and navigator objects exist which they do in normal JavaScript environments but doesn't in Google Apps Scripts.
But with some modification it's possible to get JSEncrypt to work good enough with Google Apps Scripts to sign messages using a public key.

activeandroid: multiple columns as unqiue together in a table

I am trying to make 2 columns as unique together in activeandroid using the solution provided in the link: Two column unique constraint ActiveAndroid but its just not working. Compiler is unable to find the "uniqueGroups" and "ConflictAction". I have imported Column class as well but still not working.
I am currently using activeandroid version 3.0, Looking forward to some solution. Code snippet is given below for reference
#Table(name = "Farmer")
public class Farmer extends Model {
#Column(name = "image_path")
public String image_path;
#Expose
#Column(name = "online_id")
public int online_id;
#Expose
#Column(name = "name", uniqueGroups={"group1"}, onUniqueConflicts={ConflictAction.FAIL})
public String name;
It may be a dependency issue. Check for the appropriate "compile ..." statement that you need to add to the build.gradle file for your app. For ActiveAndroid 3.1.0 you may need: compile 'com.michaelpardo:activeandroid:3.1.0-SNAPSHOT'
Also, having dependencies added to the project using gradle compile statements like the one above AND jar file dependencies may cause conflicts. Choose one of the two methods to avoid that.

Copy constructor using private attributes

My first question here so be gentle.
I would like arguments for the following code:
public class Example {
private String name;
private int age;
...
// copy constructor here
public Example(Example e) {
this.name = e.name; // accessing a private attribute of an instance
this.age = e.age;
}
...
}
I believe this breaks the modularity of the instance passed to the copy constructor.
This is what I believe to be correct:
public class Example {
private String name;
private int age;
...
// copy constructor here
public Example(Example e) {
this.setName(e.getName());
this.setAge(e.getAge());
}
...
}
A friend has exposed a valid point of view, saying that in the copy construct we should create the object as fast as possible. And adding getter/setter methods would result in unnecessary overhead.
I stand on a crossroad. Can you shed some light?
Access is class based, not object based.
The rationale for making a member private is that the ther classes should not know the details of implementation outside of well defined API, so as to make the rest of the system tolerate the change of implementation. However, the copy constructor is not "the rst of the system" - it is your own class.
The first example is not copying a private attribute of an instance, because they are bot instances of the same class.
However, if you add access methods/properties, any decent compiler should optimise them away to simple "inlines", in which case the second method is cleaner code (all accesses go via your access function) but both approaches should end us as be equally efficient (probably identical) memberwise copies.
If you really want a copy constructor to be efficient, then a lower level binary copy will be faster than a memberwise copy. But significantly "dirtier".
In general I prefer to access all member fields via properties/accessors as that encapsulates them better, allowing you to change the underlying implementation/storage of a field without having to change any of the code that accesses it, except for the property/accessor itself.