Web Crypto API – ECDH - Possible to import private key with only the private key component, without the public key components? - webcrypto-api

Given a P-256 Elliptical Curve Diffie-Hellman Private Key (which is simply a random 256-bit integer): is it possible to import this private key into a CryptoKey object, using the window.crypto.subtle.importKey() method of the Web Crypto API – without having the public key components?
I know that it’s possible to import the private key if the public key components (which are derived from the private key component) are available as well. For example, the code below runs successfully:
window.crypto.subtle.importKey(
"jwk", //can be "jwk" (public or private), "raw" (public only), "spki" (public only), or "pkcs8" (private only)
{
"crv":"P-256",
"d":"eM8u2176zFk9bwDP_jbJqnm-TlSo6GX702D9I_1AqBU",
"ext":true,
"key_ops":["deriveKey","deriveBits"],
"kty":"EC",
"x":"5Uw_SuaGZTFAuQuDArnLEmmyp4TpHx3AlBxL4EUEzbQ",
"y":"RO5t581VBuAKTQZVPSB__ebV6y9GCzrl8lBV2-p9BlM"
},
{ //these are the algorithm options
name: "ECDH",
namedCurve: "P-256", //can be "P-256", "P-384", or "P-521"
},
true, //whether the key is extractable (i.e. can be used in exportKey)
["deriveKey"] //"deriveKey" and/or "deriveBits" for private keys only (just put an empty list if importing a public key)
)
.then(function(key) {
console.log(key);
})
.catch(function(err){
console.error(err);
});
However, if only the private key component is available, without the public key components, as in the code below, the Web Crypto API throws a DOMException with the message ‘Data provided to an operation does not meet requirements’.
window.crypto.subtle.importKey(
"jwk", //can be "jwk" (public or private), "raw" (public only), "spki" (public only), or "pkcs8" (private only)
{
"crv":"P-256",
"d":"eM8u2176zFk9bwDP_jbJqnm-TlSo6GX702D9I_1AqBU",
"ext":true,
"key_ops":["deriveKey","deriveBits"],
"kty":"EC"
},
{ //these are the algorithm options
name: "ECDH",
namedCurve: "P-256", //can be "P-256", "P-384", or "P-521"
},
true, //whether the key is extractable (i.e. can be used in exportKey)
["deriveKey"] //"deriveKey" and/or "deriveBits" for private keys only (just put an empty list if importing a public key)
)
.then(function(key) {
console.log(key);
})
.catch(function(err){
console.error(err);
});
I’ve also tried using pkcs8 format for the key, instead of JWK, but no luck there either.
The documentation for the Web Crypto API shows that it is possible to import a ECDH private key in JWK format – so, it seems that it should be possible to do so without the public key components as well (the Web Crypto API should be able to calculate the public key components, if needed, from the private key component internally, as it seems to do with the .generateKey() method). However, the importKey() method seems to only work if the public key components are included.
Am I missing something here? If not, does anyone know of a solution or workaround, short of calculating the public key components separately prior to importing, and including them with the private key component in the importKey() method (which seems overly cumbersome and unnecessary)?

You can always derive the public point from the private key by scalar multiplying the private key with the base point (or the generator point) of the curve you chosen. How you complete this depends on your run-time environment.

If you have the pkcs8 format you can use this:
crypto.subtle.importKey("pkcs8", [privateKeyBuffer],{name:"ECDH",namedCurve:"P-256"} , true, ["deriveKey"]);

Related

Implementing multiple overloaded functions vs doing inside checking/validation for enforcing business logic

This is a general issue, but i will demonstrate it using the following problem:
I want to model airCrafts. now, for every aircraft there is one capability that is loaded with: attackCapability, IntelligenceCapability and BdaCapability. Not all aircraft can be loaded with all capabilities - every airCraft has its own potential capabilities that is supports and can be loaded with.
I want to implement this business logic with composition:
every aircraft object will hold a private member of type Capability (every capability will be implemented by a class that inherits from this abstract class/interface).
Now - I want to design a code that will enforce the business logic - i.e. will not allow any programmer to load an aircraft with an ability it doesn't support.
I have two options for doing this:
implement several overloaded version of the SetCapability() function - each one with the type of capability i want to support. For example:
public void SetCapability(AttackCapability capability);
public void SetCapability(BdaCapability capability);
That way the user can't load the aircraft with forbidden capability - and if he/she will try doing so, there will be a compilation erorr - i.e. that IDE will show some error message.
implement one function: public void SetCapability(Capability capability)
and doing some checking inside it. something like this:
public void SetCapability(Capability capability){
if(capability.getType() != typeOf(AttackCapability) || capability.getType() != typeOf(BdaCapability){
throw new InvalidOperationException();
}
_capability = capability;
}
the disdvantage here is that misuse of the user will be identified only at runtime instead at compiletime (much harder to identify and more bug prone), but as opposed to the previous option - it doesn't make you write several overloaded function which may cause the class to look heavy, strange and less readable for the inexperienced programmer.
(code reusability is not a big issues, because we always can implement private function like: private void SetCapabiltiy(Capability capability); which do the setting logic and every public overloaded SetCapability function will call it).
I feel that both option have their advantages and disadvantages as i described above.
I tend to prefer the first one, because it is more safe and hermeric - but it frequently causes my code to look "ugly" and some programmers may interprete it as duplicated code and don't understand the point...
I would like to hear your opinion for this issues, and maybe you have some better designs for this problem.
I couldn't understand your #1 option, but I think in any option you said you need to check permitted capabilities statically. This would result to change the code in future and would break the OCP. Instead of this I thought that maybe we can take advantage of dynamic dispatch here and let it to check types.
IMHO you can create final concrete classes and set required access modifiers to private in the concretes and then use factories(actually the abstract factory pattern looks suitable here) to hide object creation from clients to enforce business logic and the use the technique(which is my term) that referencing the same type used in Decorator or Chain of Responsibility patterns to keep capabilities in a chain by which you may have extra possibilities to dynamically check the capabilities to apply the behavior they require instead of just in a list( which could be used with Command pattern also)
As a note, the section where you mention as your second option limits the extensibility and generally manual type check is considered as bad practice in a dynamically dispatched or duck typed OOP language runtime. I know the fact that you are checking the field not a type but this is also a manual control and capability as the name implies is a behavior not state.
Finally since the aircrafts don't have same functionalities, but varying behaviors Visitor pattern could be used to design functionalities by which you create method classes instead of classes containing methods.
In addition, a Map<Aircraft, List<Capability>> could be used by keeping in a config object chek the features when creating objects by using DI.
//Capability types
interface Capable {
do();
}
class Attacker implements Capable {
private Capable capability;
public Attacker(Capable capability) { //to keep track of next/linked capability
this.capability = capability;
}
public do(String request) {
this.attack();
this.capability.do();//or instead of this decorator you could use chain of responsibility with next() and handle() below.
}
//to select features in some functionality.
public handle(String request) {
if ("attack".equals(request)) { //just to show what you can by keeping a reference to same type
this.attack();
} else {
this.capability.do();
}
}
public next(Capable capability) {
this.capability = capability;
}
}
class Intelligent implements Capable {
//similar to above.
}
//Aircraft types
class F111 implements Aircraft {
private Capable capability;
//or store capabilities in a list and check with config mapper object(maps aircrafts with its capabilities in a Map<Aircraft.TYPE, List<Capable> capabilities)
//private List<Capable> capabilities;
//other state
Aircraft(Capable capability) { //or create a factory
this.capability = capability;
}
//behaviors
doSth() {
this.capability.do();
}
}
class F222 implements Aircraft {
//...
}
//To hide creation of requested aircraft with only its required capabilities from the client
static class AircraftFactory { //dont permit to directly access to Aircraft concretes
static Aircraft getAircraft(String type) {//could be used abstract factory instead of this.
if("f111".equals(type)) {
return new F111(new Attacker(new Intelligent()));
}
else if(...) { new F222(new Intelligent(new Bda())}
else if(...) { new F001(new Default()) }
}
}
class Client {
main() {
//instead of this
//Aircraft f9999 = new Aircraft(new Attacker);
//f9999.doSth();
//enforce client to use factory.
Aircraft aircraft = AircraftFactory.getAircraft("f222");
aircraft.doSth();
}
}

Multiple MemoryCache in ASp .Net Core Web API

I have an ASP .Net Core 2.2. Web API. I'd like to speed up performance by using MemoryCache. However, I need to cache 2 different types, both which use integer keys. The one type is a list of users and the other is a list of groups.
Now, I'm adding the MemoryCache service in the Startup.cs file:
services.AddMemoryCache();
and then I'm using dependency injection to access this cache in two different places (in Middleware and in a service I wrote).
From what I understand, both these caches are the same instance. So when I add my various users and groups to it, since they both have integer keys, there will be conflicts. How can I handle this? I thought about using two caches - one for each type - but (a) I'm not sure how to do this and (b) I've read somewhere that it's not recommended to use multiple caches. Any ideas?
Yeah, I've had the same issue before and resorted to creating an extended version of the MemoryCache that allows me to plug in different "stores".. You can do it simply by wrapping the data you're sticking into the cache in a "metadata" type class. I suppose similar to how the ServiceDescriptors wrap your service registrations in the DI?
Also, in specific answer to the point "I thought about using two caches - one for each type". This is where the problem will arise because I believe IMemoryCache gets registered as a singleton by default
I ran into this problem myself. One solution I thought of was to just two instantiate separate memory caches in a wrapper class and register the wrapper class as a singleton instance. However, this only makes sense if you have different requirements for each memory cache and/or you expect to store a massive amount of data for each memory cache (at that point, an in-memory cache may not be what you want).
Here is some example classes I want to cache.
// If using a record, GetHashCode is already implemented through each member already
public record Person(string Name);
// If using a class, ensure that Equals/GetHashCode is overridden
public class Car
{
public string Model { get; }
public Car(string model)
{
Model = model;
}
public override bool Equals(object? obj)
{
return obj is Car car &&
Model == car.Model;
}
public override int GetHashCode()
{
return HashCode.Combine(Model);
}
}
Here is a dual MemoryCache implementation.
public class CustomCache : ICustomCache // Expose what you need and register it as singleton instance
{
private readonly MemoryCache personCache;
private readonly MemoryCache carCache;
public CustomCache(IOptions<MemoryCacheOptions> personCacheOptions, IOptions<MemoryCacheOptions> carCacheOptions)
{
personCache = new MemoryCache(personCacheOptions);
carCache = new MemoryCache(carCacheOptions);
}
public void CreatePersonEntry(Person person)
{
_ = personCache.Set(person, person, TimeSpan.FromHours(1));
}
public void CreateCarEntry(Car car)
{
_ = carCache.Set(car, car, TimeSpan.FromHours(12));
}
}
If you don't have the above requirements, then you could just do what juunas mentioned and create an easy wrapper with a composite key. You still need to ensure GetHashCode is properly implemented for each class you want to store. Here, my composite key is just an integer (I used prime numbers, no specific reason) paired with an object. I didn't use a struct for the key as the MemoryCache uses a Dictionary<object, CacheEntry>, so I don't want to box/unbox the key.
public class CustomCache : ICustomCache // Expose what you need
{
private readonly IMemoryCache cache;
public CustomCache(IMemoryCache cache)
{
this.cache = cache;
}
public void CreatePersonEntry(Person person)
{
_ = cache.Set(CustomKey.Person(person), person, TimeSpan.FromHours(1));
}
public void CreateCarEntry(Car car)
{
_ = cache.Set(CustomKey.Car(car), car, TimeSpan.FromHours(12));
}
private record CompositeKey(int Key, object Value)
{
public static CustomKey Person(Person value) => new(PERSON_KEY, value);
public static CustomKey Car(Car value) => new(CAR_KEY, value);
private const int PERSON_KEY = 1123322689;
private const int CAR_KEY = 262376431;
}
}
Let me know if you see anything wrong, or if there is a better solution.

Auto generate unique IDs using the singleton pattern

The small piece of code I present is in C#, but the question is more about theory and design (I think) than about code itself.
In my application, a user can add items (let's say it is a wish list manager and the user can add his wishes). I am required to auto generate IDs for this entries.
They gave us an example about how to do this and we have to use it (from what I've read around here, GUIDs are a great way of doing this and I'll have gone for that if the choice was mine, but this is irrelevant here).
The given example:
class IDGenerator
{
private static IDGenerator instance;
private int nextID;
private IDGenerator() { nextID = 1; }
[MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
public static IDGenerator getGenerator()
{
if (instance == null)
{
instance = new IDGenerator();
}
return instance;
}
public int nextId()
{
return nextID++;
}
}
Then, the teacher has a IdObject class from which Wish inherits and every time a new instance of Wish is created, a unique ID is generated using the above IdGenerator. Pretty simple. It is basically like a wrapper around a global variable.
I have some problems with this: the IDs are not reusable (not such a big problem), if I want to have another class that extends IdObject I need another id generator (done by simply copy pasting the code or I can just live with the fact that I'll have IDs all over the place).
But the biggest problem I have: if I save the wish list (simply text file, serialization, it doesn't matter) I can end up with duplicate IDs. I could work around this by enforcing a file reading every time the program starts, check the IDs, and then initialize the first next ID with a value outside the range of already used IDs and then enforce a file save every time a item is added. Or I can just keep generating IDs until a valid one is generated. But I don't want to do it like this. There must be a better way of doing it.
So any good ways of doing this by still using the singleton pattern and not doing "magic tricks" like the ones I described above?
OK. So the question is how do I ensure that the IDGenerator will not repeat the initial sequence over and over again every time it is resumed, right? As you pointed it out, one solution would be to use a sufficiently strong random generator; the other one would require persisting its state.
So the question becomes: persist or randomize, isn't there any other solution? And the answer is yes.
For instance, every time you resume your generator you could initialize its nextId variable to the current timestamp expressed in seconds (I don't think milliseconds would be necessary.) That way there won't be any repetitions. Of course, you would leave large intervals of unused ids between sessions, but this could be seen as the price you would be glad to pay if you want to keep the generator's code as simple as possible.
public sealed class SingletonIdGenerator
{
private static long _id;
private SingletonIdGenerator()
{
}
public string Id
{
get { return _id++.ToString().Substring(8); }
}
public static SingletonIdGenerator Instance { get { return Nested.instance; } }
private class Nested
{
static Nested()
{
_id = DateTime.Now.Ticks;
}
internal static readonly SingletonIdGenerator instance = new SingletonIdGenerator();
}
}

DataNucleus JDO reverse datastore 1:1 mapping with foreign keys

I have a DataNucleus project and I am using JDO to reverse map a datastore to my classes. I do this very easily with:
package com.sample;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;
#PersistenceCapable(table = "source")
public class Source {
#PrimaryKey
private String source_id;
private Topic topic_id;
private String url;
private String description;
// getters and setters
}
public class Topic {
private String topic_id;
private String topicName;
private String topicDescription;
// getters and setters
}
The topic_id is a foreign key to another table, topic, which contains an id, a topicName, and a topicDescription.
I know that it is possible, using annotations, to return topic.id, topic.topicName, and topic.topicDescription with the topic_id. I just cannot figure out how, and I find the documentation to be a bit cryptic, especially for reverse mapping.
Can anyone lend a hand and provide an example? I've tried playing around with the #ForeignKey and #Element annotations, but I haven't had any luck yet.
Thanks!
If the "topic_id" is a FK to another object (which isn't posted), then the Java class should have a Topic object field in there, like any normal 1-1 (Object-Oriented) relation

The Object-Oriented way to separate the model from its representation

Suppose we have an object that represents the configuration of a piece of hardware. For the sake of argument, a temperature controller (TempController). It contains one property, the setpoint temperature.
I need to save this configuration to a file for use in some other device. The file format (FormatA) is set in stone. I don't want the TempController object to know about the file format... it's just not relevant to that object. So I make another object, "FormatAExporter", that transforms the TempController into the desired output.
A year later we make a new temperature controller, let's call it "AdvancedTempController", that not only has a setpoint but also has rate control, meaning one or two more properties. A new file format is also invented to store those properties... let's call it FormatB.
Both file formats are capable of representing both devices ( assume AdvancedTempController has reasonable defaults if it lacks settings ).
So here is the problem: Without using 'isa' or some other "cheating" way to figure out what type of object I have, how can FormatBExporter handle both cases?
My first instinct is to have a method in each temperature controller that can provide a customer exporter for that class, e.g., TempController.getExporter() and AdvancedTempController.getExporter(). This doesn't support multiple file formats well.
The only other approach that springs to mind is to have a method in each temperature controller that returns a list of properties and their values, and then the formatter can decide how to output those. It'd work, but that seems convoluted.
UPDATE: Upon further work, that latter approach doesn't really work well. If all your types are simple it might, but if your properties are Objects then you end up just pushing the problem down a level... you are forced to return a pair of String,Object values, and the exporter will have to know what the Objects actually are to make use of them. So it just pushes the problem to another level.
Are there any suggestions for how I might keep this flexible?
What you can do is let the TempControllers be responsible for persisting itself using a generic archiver.
class TempController
{
private Temperature _setPoint;
public Temperature SetPoint { get; set;}
public ImportFrom(Archive archive)
{
SetPoint = archive.Read("SetPoint");
}
public ExportTo(Archive archive)
{
archive.Write("SetPoint", SetPoint);
}
}
class AdvancedTempController
{
private Temperature _setPoint;
private Rate _rateControl;
public Temperature SetPoint { get; set;}
public Rate RateControl { get; set;}
public ImportFrom(Archive archive)
{
SetPoint = archive.Read("SetPoint");
RateControl = archive.ReadWithDefault("RateControl", Rate.Zero);
}
public ExportTo(Archive archive)
{
archive.Write("SetPoint", SetPoint);
archive.Write("RateControl", RateControl);
}
}
By keeping it this way, the controllers do not care how the actual values are stored but you are still keeping the internals of the object well encapsulated.
Now you can define an abstract Archive class that all archive classes can implement.
abstract class Archive
{
public abstract object Read(string key);
public abstract object ReadWithDefault(string key, object defaultValue);
public abstract void Write(string key);
}
FormatA archiver can do it one way, and FormatB archive can do it another.
class FormatAArchive : Archive
{
public object Read(string key)
{
// read stuff
}
public object ReadWithDefault(string key, object defaultValue)
{
// if store contains key, read stuff
// else return default value
}
public void Write(string key)
{
// write stuff
}
}
class FormatBArchive : Archive
{
public object Read(string key)
{
// read stuff
}
public object ReadWithDefault(string key, object defaultValue)
{
// if store contains key, read stuff
// else return default value
}
public void Write(string key)
{
// write stuff
}
}
You can add in another Controller type and pass it whatever formatter. You can also create another formatter and pass it to whichever controller.
In C# or other languages that support this you can do this:
class TempController {
int SetPoint;
}
class AdvancedTempController : TempController {
int Rate;
}
class FormatAExporter {
void Export(TempController tc) {
Write(tc.SetPoint);
}
}
class FormatBExporter {
void Export(TempController tc) {
if (tc is AdvancedTempController) {
Write((tc as AdvancedTempController).Rate);
}
Write(tc.SetPoint);
}
}
I'd have the "temp controller", through a getState method, return a map (e.g. in Python a dict, in Javascript an object, in C++ a std::map or std::hashmap, etc, etc) of its properties and current values -- what's convoluted about it?! Could hardly be simpler, it's totally extensible, and totally decoupled from the use it's put to (displaying, serializing, &c).
Well, a lot of that depends on the file formats you're talking about.
If they're based on key/value combinations (including nested ones, like xml), then having some kind of intermediate memory object that's loosely typed that can be thrown at the appropriate file format writer is a good way to do it.
If not, then you've got a scenario where you've got four combinations of objects and file formats, with custom logic for each scenario. In that case, it may not be possible to have a single representation for each file format that can deal with either controller. In other words, if you can't generalize the file format writer, you can't generalize it.
I don't really like the idea of the controllers having exporters - I'm just not a fan of objects knowing about storage mechanisms and whatnot (they may know about the concept of storage, and have a specific instance given to them via some DI mechanism). But I think you're in agreement with that, and for pretty much the same reasons.
If FormatBExporter takes an AdvancedTempController, then you can make a bridge class that makes TempController conform to AdvancedTempController. You may need to add some sort of getFormat() function to AdvancedTempController though.
For example:
FormatBExporter exporterB;
TempController tempController;
AdvancedTempController bridged = TempToAdvancedTempBridge(tempController);
exporterB.export(bridged);
There is also the option of using a key-to-value mapping scheme. FormatAExporter exports/imports a value for key "setpoint". FormatBExporter exports/imports a values for keys "setpoint" and "ratecontrol". This way, old FormatAExporter can still read the new file format (it just ignores "ratecontrol") and FormatBExporter can read the old file format (if "ratecontrol" is missing, it uses a default).
In the OO model, the object methods as a collective is the controller. It's more useful to separate your program in to the M and V and not so much the C if you're programming using OO.
I guess this is the where the Factory method pattern would apply