How to extract public and private key from RSA JWK? - encryption

I'm trying to sign some data with a JWK i've been provided with.
So far i've tried to do this with jwt.io, the header is
{ "alg" : "RS256", "typ" : "JWT" }
and the payload is
{ "iss" : "4#john" }
Now to sign this I need a public and a private key. I've been told to extract these from the JWK provided, but i only seem to be able to extract a public key from this.
I've used jwk-to-pem but when provided with the JWK it only puts out the public key. But to sign with RS256 i need a public and a private key, i thought the private key is embedded into the JWK but i can't seem to extract it.
So my question is, how to extract the public AND private key from the JWK?
The JWK looks like this:
"ServicePrincipalKey": {
"k": null,
"kid": "urn:service:john:doe:4",
"kty": "RSA",
"use": null,
"n": "rT-...skQ",
"e": "A...B",
"x5t": null,
"d": "CP9...bsQ",
"p": "7dG...PDk",
"q": "un4...oxk",
"dp": "HdF...m4Xk",
"dq": "XGN...PMk",
"qi": "0es...UDI",
"nbf": "0001-01-01T00:00:00",
"exp": "0001-01-01T00:00:00"
}

Found the answer for jwk-to-pem. There is an option to generate a private and public key.
on runkit i executed the following code:
var jwkToPem = require("jwk-to-pem")
var jwk = {
"k": null,
"kid": "urn:service:john:doe:4",
"kty": "RSA",
"use": null,
"n": "rT-...skQ",
"e": "A...B",
"x5t": null,
"d": "CP9...bsQ",
"p": "7dG...PDk",
"q": "un4...oxk",
"dp": "HdF...m4Xk",
"dq": "XGN...PMk",
"qi": "0es...UDI",
"nbf": "0001-01-01T00:00:00",
"exp": "0001-01-01T00:00:00"
}
var publicPEM = jwkToPem(jwk);
console.log(publicPEM);
var options = {"private" : true} //important this will set jwkToPem to output the private key
var privatePEM = jwkToPem(jwk, options);
console.log(privatePEM);
This outputs a public and a private key into the console.
Now by filling in these public and private keys into jwt.io i was able to generate a JWT

Related

Why my JSON format change after set it to the entities redux toolkit

I have current problem in my entity adapter after I receive the response from the api and set the payload to the state it happen is the json format change. I don't know if the setOne method of redux toolkit change it by self.
Original Format :
{
"id": "af3fbedf-4751-413b-abd5-074737b6edd2",
"role_id": null,
"first_name": "Geirge",
"last_name": "Shaw",
"email": "sdf#sdf.com",
"email_verified_at": null,
"username": "coder",
"status": 1,
"created_at": "2021-11-18T06:50:46.000000Z",
"created_by": null,
"updated_at": "2021-11-18T06:50:46.000000Z",
"updated_by": null,
"fullname": "Geirge Shaw",
"token": "94|4O0z51gddqHxeCs5UhLysE9QoSsIOSlP2EYb9iFQ"
}
New Format after I set the response to the state:
af3fbedf-4751-413b-abd5-074737b6edd2: {id: 'af3fbedf-4751-413b-abd5-074737b6edd2', role_id: null, first_name: .....}
ExtraReducers Looks Like:
extraReducers: {
[LoginAuthentication.pending](state, action){
state.isLoading = true
state.isLoggedIn = false
},
[LoginAuthentication.fulfilled](state, {payload}){
console.log(payload);
state.isLoading = false
LoginAdapter.setOne(state, payload)
state.isLoggedIn = true
},
[LoginAuthentication.rejected](state, action) {
state.isLoading = false
state.isLoggedIn = false
}
}
Because that is exactly what createEntityAdapter does. It takes the original item objects, and stores them in a lookup table where the keys are the IDs and the values are the original items.
See these resources for more explanations:
https://redux.js.org/usage/structuring-reducers/normalizing-state-shape
https://redux.js.org/tutorials/essentials/part-6-performance-normalization
https://redux.js.org/tutorials/fundamentals/part-7-standard-patterns#normalized-state
https://redux.js.org/tutorials/fundamentals/part-8-modern-redux#using-createentityadapter
https://redux-toolkit.js.org/usage/usage-guide#managing-normalized-data
https://redux-toolkit.js.org/api/createEntityAdapter

Spatial Point data type is not serialized correctly when using custom System.Text.Json serializer for Cosmos .NET v3 SDK

I want to use the System.Text.Json Json serializer with the Cosmos .NET v3 SDK.
So I use:
var client = new CosmosClientBuilder
(accountEndpoint: "https://localhost:8081", "<key>")
.WithCustomSerializer(new SystemTextJsonCosmosSerializer(new JsonSerializerOptions {}))
.Build();
With the custom serializer being (taken from Github issue):
public class SystemTextJsonCosmosSerializer : CosmosSerializer
{
private readonly JsonSerializerOptions _options;
public SystemTextJsonCosmosSerializer(JsonSerializerOptions options)
{
_options = options;
}
/// <inheritdoc />
public override T FromStream<T>(Stream stream)
{
// Have to dispose of the stream, otherwise the Cosmos SDK throws.
// https://github.com/Azure/azure-cosmos-dotnet-v3/blob/0843cae3c252dd49aa8e392623d7eaaed7eb712b/Microsoft.Azure.Cosmos/src/Serializer/CosmosJsonSerializerWrapper.cs#L22
// https://github.com/Azure/azure-cosmos-dotnet-v3/blob/0843cae3c252dd49aa8e392623d7eaaed7eb712b/Microsoft.Azure.Cosmos/src/Serializer/CosmosJsonDotNetSerializer.cs#L73
using (stream)
{
// TODO Would be more efficient if CosmosSerializer supported async
using var memory = new MemoryStream((int)stream.Length);
stream.CopyTo(memory);
byte[] utf8Json = memory.ToArray();
return JsonSerializer.Deserialize<T>(utf8Json, _options);
}
}
/// <inheritdoc />
public override Stream ToStream<T>(T input)
{
byte[] utf8Json = JsonSerializer.SerializeToUtf8Bytes(input, _options);
return new MemoryStream(utf8Json);
}
}
However, the Point data type is then not properly serilized.
public Point Location { get; set; }
It should be (as with Cosmos .NET SDK v3/Newtonsoft , v4 Preview/System.Text.Json) be:
"location": {
"type": "Point",
"coordinates": [
8.0000,
47.0000
]
},
But instead it ends up being:
"location": {
"Position": {
"Coordinates": [
8.0000,
47.0000
],
"Longitude": 8.0000,
"Latitude": 47.0000,
"Altitude": null
},
"Crs": {
"Type": 0
},
"Type": 0,
"BoundingBox": null,
"AdditionalProperties": {}
},
Anyone has idea on why, and how I can make it serialize properly?

Enter a name instead of user id

I have 2 tables.
first table name is user.
User_id, User_name
Second table name is Question
Question_id, Question, User_id
I want to see the user name when I call the Question table.
table connection code:
public function user()
{
return $this->belongsTo(User::class);
}
And resource code is:
public function toArray($request)
{
return[
'Question' => $this->Question,
'created_at' => $this->created_at->diffForHumans(),
'user' => $this->user->name
];
}
Question controller show function:
public function show(Question $question)
{
return new QuestionResource($question);
}
The error during operation in the following code:
{
"message": "Class 'App\\Model\\User' not found",
"exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
"file": "C:\\xampp\\htdocs\\forumapp\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Concerns\\HasRelationships.php",
"line": 718,
"trace": [
{
"file": "C:\\xampp\\htdocs\\forumapp\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Concerns\\HasRelationships.php",
"line": 179,
"function": "newRelatedInstance",
"class": "Illuminate\\Database\\Eloquent\\Model",
"type": "->"
},
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'user';
}
Create an Elquoent model class because you have used 'return $this->belongsTo(User::class);' User class here to define elquoent relation.
Hope it will work for you.

API Gateway and DynamoDB PutItem for String Set

I can't seem to find how to correctly call PutItem for a StringSet in DynamoDB through API Gateway. If I call it like I would for a List of Maps, then I get objects returned. Example data is below.
{
"eventId": "Lorem",
"eventName": "Lorem",
"companies": [
{
"companyId": "Lorem",
"companyName": "Lorem"
}
],
"eventTags": [
"Lorem",
"Lorem"
]
}
And my example template call for companies:
"companies" : {
"L": [
#foreach($elem in $inputRoot.companies) {
"M": {
"companyId": {
"S": "$elem.companyId"
},
"companyName": {
"S": "$elem.companyName"
}
}
} #if($foreach.hasNext),#end
#end
]
}
I've tried to call it with String Set listed, but it errors out still and tells me that "Start of structure or map found where not expected" or that serialization failed.
"eventTags" : {
"SS": [
#foreach($elem in $inputRoot.eventTags) {
"S":"$elem"
} #if($foreach.hasNext),#end
#end
]
}
What is the proper way to call PutItem for converting an array of strings to a String Set?
If you are using JavaScript AWS SDK, you can use document client API (docClient.createSet) to store the SET data type.
docClient.createSet - converts the array into SET data type
var docClient = new AWS.DynamoDB.DocumentClient();
var params = {
TableName:table,
Item:{
"yearkey": year,
"title": title
"product" : docClient.createSet(['milk','veg'])
}
};

Jquery Datatables Ajax Response

I am trying to follow the datatable example for Ajax data source (objects) found here. I am using asp.net and have the following handler which receives my data, processes it and provides the response.
public class UsersHandler : IHttpHandler
{
private const string JsHeader = #"{{""data"" {0}}}";
public void ProcessRequest(HttpContext context)
{
IEnumerable<SystemUser> data = SystemUserLogic.LoadAllSystemUsers();
List<SimpleUser> userlist = new List<SimpleUser>();
foreach (SystemUser su in data)
{
SimpleUser simple = new SimpleUser();
simple.Id = su.Id;
simple.FullName = su.NameFirst;
simple.Email = "example#email.co.uk";
userlist.Add(simple);
}
string json = JsonConvert.SerializeObject(userlist, Formatting.Indented);
context.Response.ContentType = "text/plain";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Cache.SetNoStore();
context.Response.Expires = -1;
context.Response.Write(String.Format(JsHeader, json));
}
which deliveries the correct response when I catch it in the browser and look at the data via the network traffic. My aspx page contains the following.
$('#table_id').DataTable({
"ajax": '/Handlers_New/UsersHandler.ashx',
"columns": [
{ "data": "Id" },
{ "data": "FullName" },
{ "data": "Email" },
{ "data": "KeyResource" }
]
});
However when the page loads, I am getting this error:
DataTables warning: table id=table_id - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
The outputted data looks like this,
{"data" [
{
"Id": 1,
"FullName": "Admin",
"Email": "example#email.co.uk",
"KeyResource": false
},
{
"Id": 2,
"FullName": "Jon",
"Email": "example#email.co.uk",
"KeyResource": false
},
{
"Id": 3,
"FullName": "Stephen",
"Email": "example#email.co.uk",
"KeyResource": false
}, etc.....
Please tell me why I am getting this error. Should I be manipulating the json object differently, or am I missing something with the Jquery datatables?
I have managed to fix my issue amazingly due to jsonlint. I ran my code through that and it turns out I was missing a ':' in my jsHeader. So what I had was:
private const string JsHeader = #"{{""data"" {0}}}";
and what I have now which now works is:
private const string JsHeader = #"{{""data"": {0}}}";
Hope this helps any one else encountering a similar issue.

Resources