How can I extract alternative names data from a CSR? - javascript

I have a CSR and I can parse all the data with pkijs.org lib, but I have no luck to parse alternative names data. How is it possible to do with a javascript? Some other libs can be in use, I guess, do you know one?

Following the docs of CertificationRequest class provided by pkijs here https://pkijs.org/docs/classes/CertificationRequest.html. We can see that the structure of a CSR. The subject alternative name will be stored in attributes propery of CertificationRequest object. But the structure inside of attributes is quite complex to make it as plain text. This is my code used to print out the subject alternative name
const pkijs = require('pkijs');
const utils = require("pvtsutils");
const asn1js = require("asn1js");
let base64 = "<your_csr_in_base64>"
let csrraw = utils.Convert.FromBase64(base64);
console.log(csrraw)
const pkcs10 = pkijs.CertificationRequest.fromBER(csrraw);
let seq = pkcs10.attributes[0].values[0];
let exts = pkijs.Extensions.fromBER(seq.toBER(false));
console.log(exts);
var san = getExtentionsForSANFromExtensions(exts);
console.log(san)
if (san != undefined) {
san.names.forEach(element => {
console.log(element.type + " = " + element.value)
});
}
function getExtentionsForSANFromExtensions(exts){
for (var i = 0 ; i< exts.extensions.length; i++) {
var ext = exts.extensions[i];
if(ext.extnID == '2.5.29.17') {
var octetString = asn1js.fromBER(ext.extnValue.toBER(false)).result;
return pkijs.GeneralNames.fromBER(octetString.getValue());
}
}
}
I've tested this code and it works properly with CSR generated by Keystore Explorer. Have not tested with another tool to generate CSR that supports subject alternative names.
Cheers!

If you have a CSR and need to extract the alternative names data from it, you can use the following command:
openssl req -in csr.pem -noout -text
This will print out the entire CSR, including the alternative names data.

Related

require() not working with variable - react native

I meet a weird problem. If I set a variable direclty with a value like this "const myString = 'someWord';" that work but if I take the value from a variable like this "const myString = someVariable;", that doesn't work, and if I set the value on a conditional block that doesn't work too.
So, work:
var jsonName = 'tramwayen';
const pathex = require('../assets/JSON/' + jsonName);
var json = JSON.parse(JSON.stringify(pathex));
doesn't work:
var jsonName = variable;
const pathex = require('../assets/JSON/' + jsonName);
var json = JSON.parse(JSON.stringify(pathex));
doesn't work:
var jsonName = '';
if (condition) {
jsonName = 'tramwayen';
}
const pathex = require('../assets/JSON/' + jsonName);
var json = JSON.parse(JSON.stringify(pathex));
I really don't understand.
I have this error :
"Invalid call at line 41: require('../assets/JSON/' + jsonName2)"
Most JS bundlers cannot handle dynamic require imports. You might want to load all of the files, and put them in an object:
let data = {
tramwayen: require('../assets/JSON/tramwayen.json'),
something: require('../assets/JSON/something.json'),
// and so on
};
And use the data object to retrieve the data you need.
From what I read while doing some research, it seems impossible to made a require dynamically. In react native require should be static.
But there are some solutions to avoid this issue.
Here is mine, I put all data of my differents Json on one single json, and I dynamically choice wich part of the data I want to get.
I can also, put all the static require on an object, and choose dynamicaly wich require I want to get.
solution 1:
const id = window.currentPI;
const json = require('../assets/JSON/mainData.json');
const nbreOfPix = json[`${id}`].preData.numberOfPictures;
solution 2:
const IMAGES = {
tramwayen: require('../assets/CtrlPI/PHOTO_articles/008_02_Img.png'),
tramwayen2: require('../assets/CtrlPI/PHOTO_articles/HC002_04_Img.png')
};
getImage = (name) => {
return IMAGES[name];
};

How to read multi part form in node.js

I have a node.js application which currently supports only x-www-form-urlencoded requests. If someone needs to send a file as an attachment I have to extend the support for form-data. Reading the data from request is currently done using DecodeURIComponent and look similar to following. Is it possible to adapt this to read form data?
exports.parseUrlEncodedBody = function(event) {
//This is to extract url encoded data
var temp = {};
if (event.body) {
// retrieve keys & values
var pm = event.body.split("&");
// store keys and values in temp object
params.forEach(function (item, index, array) {
var keyValue = item.split("=");
var key, value;
if (keyValue.length >= 1) {
key = decodeURIComponent(keyValue[0]);
if (keyValue.length >=2) {
value = decodeURIComponent(keyValue[1]);
} else {
value = "";
}
temp[key] = value;
}
});
}
Is it possible to adapt this to read form data?
No. The data format is completely different. You would need to rewrite it from scratch.
Consider using a module such as multer which is designed for this.
If you want to write your own library from scratch, then you should consult RFC 7578, which describes the data format.

How to read Java property file in AngularJS?

Is there any way to read a properties file from angularjs which resides outside the web server?
like in java the property file deployed out of the project but we can read those file in our project as filter.properties in this way any solution is there in angularJS.
I tried like this but getting undefined.
filter.properties:
key1=value1
key2=value2
sampleController.js
var app = angular.module('sampleApp', []);
app.controller('sampleController', function($scope, $http) {
$http.get('filter.properties').then(function (response) {
console.log('a is ', JSON.stringify(response.data.key1));
});
});
There are several ways to access properties files in angularjs.
Like every files properties file is a file with .properties extension.
Since java properties files are key value pair separated by = in a single line.
So we can convert a properties file into javascript object by iterating each lines in properties file and split-ing it with = symbol and storing it as javascript object which will help to access it quickly.
Here is its javascript implementation
function extractProperties(propertiesFileContents){
var keyValuePairs =propertiesFileContents.split("\n");
properties ={}
for (i = 0; i < keyValuePairs.length; i++) {
var keyValueArr=keyValuePairs[i].trim().split("=");
var key=keyValueArr[0];
var value=keyValueArr[1];
properties[key]=value
}
return properties;
}
Based on your code here iam adding a plunker here hope this may help you
Samuel J Mathew's solution works for me, but the properties file I have to deal with have multiple empty lines in the file, together with lines commented out, and sometimes with white spaces around the = sign. So I have to add some checks to handle these situations. The modified result is such, hopefully will be useful to those working with a more complex properties file:
function extractProperties(data){
const keyValuePairs = data.split("\n");
properties = {}
for (var i = 0; i < keyValuePairs.length; i++) {
const keyValuePair = keyValuePairs[i].trim();
if (!keyValuePair || keyValuePair[0] === '#') {
continue;
}
const keyValueArr = keyValuePair.split("=");
const key = keyValueArr[0].trim();
const value = keyValueArr[1].trim();
properties[key] = value
}
return properties;
}

Generate unique id for each device

I want to generate a unique id for each device. Currently I am using fingerprint.js for this. My code is:
var fingerprint = new Fingerprint().get();
But I want to generate unique id with out using any plugins. Can any one help me please?
Friends,
At last I found the answer. This code will generate unique id for each device(in a browser) all the time. But this Id will also generate a new id if the application is opened in different browser but in same device. uid is the generated unique id.
var navigator_info = window.navigator;
var screen_info = window.screen;
var uid = navigator_info.mimeTypes.length;
uid += navigator_info.userAgent.replace(/\D+/g, '');
uid += navigator_info.plugins.length;
uid += screen_info.height || '';
uid += screen_info.width || '';
uid += screen_info.pixelDepth || '';
console.log(uid);
Thank you all for supporting me.
For example like this:
function generateUUID(){
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
};
More on the topic: Create GUID / UUID in JavaScript?
Edit:
In your comment you say, you want to generate the same id per device at any time. For such tasks, building hashes is a way to go. Get any property / properties of your device, which are unique for this device (whatever it is, it is difficult to say without example). Than build a hash out of them, for example:
var uniqueId = someHashFunction(device.property1 + device.property2 + ...);
There are plenty of hashing functions on the internet, as an example you can have a look at this one: http://phpjs.org/functions/md5/ This will return a unique value for given properties.
for node users this package helps to generate unique id
install:
npm i node-machine-id
code:
import {machineId, machineIdSync} from 'node-machine-id';
// Asyncronous call with async/await or Promise
async function getMachineId() {
let id = await machineId();
...
}
machineId().then((id) => {
...
})
// Syncronous call
let id = machineIdSync()
// id = c24b0fe51856497eebb6a2bfcd120247aac0d6334d670bb92e09a00ce8169365
let id = machineIdSync({original: true})
// id = 98912984-c4e9-5ceb-8000-03882a0485e4
You can use timestamp for a unique ID and append some static text to it:
var uniqueID = "ID-"+(new Date()).getTime().toString();

Get Query String with Dojo

Users will be hitting up against a URL that contains a query string called inquirytype. For a number of reasons, I need to read in this query string with javascript (Dojo) and save its value to a variable. I've done a fair amount of research trying to find how to do this, and I've discovered a few possibilities, but none of them seem to actually read in a query string that isn't hard-coded somewhere in the script.
You can access parameters from the url using location.search without Dojo Can a javascript attribute value be determined by a manual url parameter?
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do the following to extract id from the url /hello.php?id=5&name=value
var params = getUrlParams();
var id = params['id']; // or params.id
Dojo provides http://dojotoolkit.org/reference-guide/dojo/queryToObject.html which is a bit smarter than my simple implementation and creates arrays out of duplicated keys.
var uri = "http://some.server.org/somecontext/?foo=bar&foo=bar2&bit=byte";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = dojo.queryToObject(query);
//The structure of queryObject will be:
// {
// foo: ["bar", "bar2],
// bit: "byte"
// }
In new dojo it's accessed with io-query:
require([
"dojo/io-query",
], function (ioQuery) {
GET = ioQuery.queryToObject(decodeURIComponent(dojo.doc.location.search.slice(1)));
console.log(GET.id);
});
Since dojo 0.9, there is a better option, queryToObject.
dojo.queryToObject(query)
See this similar question with what I think is a cleaner answer.

Categories