Decrypt PHP openssl_seal output with JS Forge - javascript

I am trying to decrypt my openssl_seal stored values.
My PHP code:
public static function multiEncrypt( string $data, array $publicKeys ) : ?array
{
foreach ($publicKeys as $cert)
{
if (false === openssl_get_publickey( $cert )) {
Log::getInstance()->error('multiEncrypt : invalid pubkey ; ' . openssl_error_string());
return null;
}
}
$encryptedData = null;
$encryptedKeys = [];
$initVector = self::getInitVector( self::SEAL_CIPHER );
$result = openssl_seal(
$data,
$encryptedData,
$encryptedKeys,
$publicKeys,
self::SEAL_CIPHER,
$initVector
);
if (false === $result)
return null;
$encodedData = base64_encode( $encryptedData );
$encodedKeys = [];
foreach ($encryptedKeys as $key) {
$encodedKeys[] = base64_encode($key);
}
return [
'keys' => $encodedKeys,
'data' => $encodedData
];
}
and my client-side code:
function decrypt(privkey, blob, key)
{
var byteKey = forge.pki.privateKeyFromPem(privkey);
var usrPubKey = forge.pki.publicKeyFromPem(publicKey);
//var genPubKey = forge.pki.rsa.setPublicKey(byteKey.n, byteKey.e);
/*if (usrPubKey !== genPubKey) {
error('Your private key does not match the public key we have of you.');
return;
}*/
console.log('Decoding key..');
var decodedKey = atob(key);
console.log('Decrypting key..');
var contractUserKey = byteKey.decrypt(decodedKey);
console.log(contractUserKey);
console.log(contractUserKey.decrypt(blob));
}
However I keep getting 'forge.min.js:4068 Uncaught Error: Encryption block is invalid.'. Is there something I am missing here?

Related

How to sort endpoint data on laravel 9?

I have an endpoint (/comic/search), where the data structure looks like this:
{"item_type":"b","key_issue":null,"run":null,"bodytext":"<p>Avengers Vs the Xmen<\/p>","damaged":null,"title":"A+X","publisher":"Marvel","tags":"avengers","published":"2012-01-12","id":18,"issue":6,"stock":0,"price":1.99,"variant":"1","url":"\/books\/ax-6","cover":"http:\/\/fantasy-road.local\/assets\/img\/uploads\/20221219-172717.jpg","front":"http:\/\/fantasy-road.local\/assets\/img\/resized\/comic_flip\/20221219-172717.jpg","rear":"http:\/\/fantasy-road.local\/assets\/img\/resized\/comic_flip\/20221219-172706.jpg","summary":"Avengers Vs the Xmen","type":"Stories","relevance_score":2,"created_at":"19th\u00a0December\u00a02022"}
I have created a function in my ComicSearchController that looks like this:
use Illuminate\Http\Request;
use App\Libraries\ComicSearch;
class ComicSearchController extends Controller
{
const limit = 10;
public function getComicData(Request $request)
{
$query = $request->input('query');
$sort = $request->input('sort');
$more = ($request->has('more')) ? true : false;
$debug = ($request->has('debug')) ? true : false;
$results = ComicSearch::search($query, $more, static::limit, $debug);
// Sort the comics data if the sort parameter exists
if ($sort) {
if ($sort === 'price') {
usort($results, function ($a, $b) {
echo "Comparing " . $a['price'] . " and " . $b['price'] . "\n";
return ($a['price'] < $b['price']) ? -1 : (($a['price'] > $b['price']) ? 1 : 0);
});
} elseif ($sort === 'title') {
usort($results, function ($a, $b) {
echo "Comparing " . $a['title'] . " and " . $b['title'] . "\n";
return strcasecmp($a['title'], $b['title']);
});
}
}
return response()->json($results);
}
}
and this is being called in the vue component, with this:
sortDirection(type) {
if(type == 'alphabetUp') {
this.loading = true
this.alphabetisePlus = !this.alphabetisePlus;
this.alphabetiseMinus = false;
this.priceMinus = false;
this.pricePlus = false;
this.publishedMinus = false;
this.publishedPlus = false;
if(this.alphabetisePlus) {
axios.get('comic/search?sort=title')
.then(response => {
console.log('Before sorting:', response.data);
this.backstock = Array.from(response.data);
this.backstock.sort((a, b) => {
if(a.title < b.title) return -1;
if(a.title > b.title) return 1;
return 0;
});
console.log('After sorting:', this.backstock);
this.loading = false;
})
.catch(error => console.log(error));
}
}
the data is being returned, but exactly as it was before it was 'sorted'. Can anyone explain to me what I am doing wrong?

Programmatically modify array | Javascript

So I am trying to take data that I have collected through a REST API and decrypt is against a salt/pepper that I have already created. The below function, when $value is an array of objects, only returns the last object in the array.
encryption.decrypt() returns a string.
UPDATE have updated code with comments and I am still receiving an object instead of an array of objects.
sharedServices.encryption.decrypt = function($value) {
if(typeof $value === 'object' && $value !== null) {
$result = {};
for(var $key in $value) {
$result[$key] = sharedServices.encryption.decrypt($value[$key]);
}
return $result;
} else if(Array.isArray($value)) {
$result = new Array();
for(var $i of $value) {
$result[$i] = sharedServices.encryption.decrypt($value[$i]);
}
return $result;
} else {
$pepperSalt = sharedServices.encryption.pepper + "3" + sharedServices.encryption.salt;
let encryption = new Encryption();
return encryption.decrypt($value, $pepperSalt);
}
};
Your first if statement to check object or not is matched for array as well (Array is an object and all that). what i mean is you are always hitting the first IF for both Object & Array.
So you can switch the first and second if's, or properly check its object and not array for first if statement
Managed to get it working in the end. It now loops through objects and array preforming a function when ever it find a string/integer
sharedServices.functions.drill({
object:value,
params:{},
function: function(value, params) {return value;}
});
sharedServices.functions.drill = function(options) {
var result = null;
if(Object.prototype.toString.call(options.object) == '[object Array]') {
result = [];
angular.forEach(options.object,
function(value, key) {
console.log(key);
result.push(
sharedServices.functions.drill(
{
object: value,
params: options.params,
function: options.function
}
)
)
}
);
} else if(Object.prototype.toString.call(options.object) == '[object Object]') {
result = {};
for(var key in options.object) {
result[key] =
sharedServices.functions.drill(
{
object:options.object[key],
params: options.params,
function: options.function
}
);
}
} else {
result = options.function(options.object,options.params);
}
return result;
};

How to access object array using javascript with variable

var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
var parametersForTranslation = {};
function __tr(src, params) {
parametersForTranslation[src] = params;
return buildMessage(src);
}
function buildMessage(src){
var message=dict[src] ? dict[src].message : src
console.log(message);
var messageArray = message.split("$");
var output = "";
messageArray.forEach(function(elem, index){
if(index === 0){
output += elem;
}else{
// get variable and index
var paramIndex = configMigratedTo.substring(0, 1);
var paramValue = parametersForTranslation[src][paramIndex-1];
output += paramValue;
output += configMigratedTo.substring(1);
}
});
return output;
}
__tr("configMigratedTo", [2]);
console.log(buildMessage("configMigratedTo"));
i want get result like __tr("configMigratedTo", [2]);
then it will give me
Migrated configuration to configurator: 2
i do not know where is wrong in my code
Try this one. Hope it helps!
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
function __tr(src, params)
{
for (var key in dict)
{
if (key === src)
{
var message = dict[key].message;
return message.substring(0, message.length - 2) + params[0];
}
}
return;
}
console.log(__tr("configMigratedTo", [2]))
https://jsfiddle.net/eLd9u2pq/
Would that be enought?
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: "
}
}
function buildMessage(src,param){
var output = dict[src].message + param;
return output;
}
console.log(buildMessage("configMigratedTo",2));
You are overcomplicating this, it's much easier using a regex and passing a function as replacer
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
function __tr(src, params) {
if (! dict[src]) return src;
if (! /\$0/.test(dict[src].message)) params.unshift('');
return dict[src].message.replace(/\$(\d)+/g, (orig, match) => params[match] || orig);
}
console.log(__tr("configMigratedTo", [2]));

Multiple splits into a JSON object?

Hey guys I'm having a bit of trouble with this one, and I was hoping someone could give me a hand. I am trying to break up strings that follow this format foo.bar::baz into an object that resembles this foo.bar.baz = ''
In PHP I would do this with the following
$obj = New stdClass();
$inp = [
'type1',
'type2',
'type3.sub1::blah1',
'type3.sub2::blah1',
'type4.sub1::blah2',
'type4.sub2::blah2',
'type5.sub1',
];
foreach ($inp AS $v)
{
if (strpos($v, '.'))
{
$b = explode('.', $v);
$obj->$b[0] = '';
if (strpos($b[1], '::') && $c = explode('::', $b[1]))
{
$obj->$b[0]->$c[0]->$c[1] = '';
} else {
$obj->$b[0]->$b[1] = '';
}
} else {
$obj->$v = '';
}
}
print_r($obj);
stdClass Object
(
[type1] =>
[type2] =>
[type3] => stdClass Object
(
[sub2] => stdClass Object
(
[blah1] =>
)
)
[type4] => stdClass Object
(
[sub2] => stdClass Object
(
[blah2] =>
)
)
[type5] => stdClass Object
(
[sub1] =>
)
)
I am currently trying to mimic this in Javascript doing the following, but can't seem to get it to behave
var fieldset = results.fooresult.metadata[0].field;
var namespace = [];
// namespace from meta
for (var k in fieldset) {
if (fieldset.hasOwnProperty(k)) {
var string = fieldset[k]['$']['NAME'];
if (0<string.indexOf('.')) {
var pairs = string.split('.');
if (0<pairs[1].indexOf('::')) {
var value = pairs[1].split("::");
namespace[pairs[0]][value[0]] = value[1];
} else {
namespace[pairs[0]] = pairs[1];
}
} else {
namespace.push(string);
}
}
}
Help would be appreciated
This should work:
var inp = [
'type1',
'type2',
'type3.sub1::blah1',
'type3.sub2::blah1',
'type4.sub1::blah2',
'type4.sub2::blah2',
'type5.sub1'
];
function makeTree(inp) {
var result = {};
var split = inp.map(function (str) {
return str.split(/\.|::/);
});
var walk = function (obj, propList) {
if (propList.length == 1) {
obj[propList[0]] = '';
return;
}
var nextObj = obj[propList[0]] = obj[propList[0]] || {};
propList.shift();
walk(nextObj, propList);
};
split.forEach(walk.bind(null, result));
return result;
}
var out = makeTree(inp);

phonegap save an order at local file system

Hi I am using phonegap to develop a shopping app. I want to give the user an option to save their order and complete wheneven he/she finds convenient. My question where do I save the order data. Local file system or local db of the mobile device? I will like to save the order
in json format in a local file. Please suggest the best option for me. Also a snippet will be highly appreciated. Thanks
You could also use HTML5 localStorage as an easier alternative to file storage. I have been using an encapsulated version of localStorage to facilitate get/set operations and decrease namespace pollution. Please see code base below:
/**
* The class is designed to facilitate flexible permanent storage of key value
* pairs utilzing HTML5 localStorage.
*
* #class LocalMap
* #author Zorayr Khalapyan
* #version 10/25/2012
*/
var LocalMap = function ( name ) {
var that = {};
//Prevent compatability issues in different execution environments.
if ( !localStorage ) {
localStorage = {};
}
if ( !localStorage[name] ) {
localStorage[name] = "{}";
}
var setMap = function ( map ) {
localStorage[name] = JSON.stringify( map );
};
that.getMap = function () {
return JSON.parse( localStorage[name] );
};
/**
* Stores the specified (key, value) pair in the localStorage
* under the map's namespace.
*/
that.set = function ( name, object ) {
var map = that.getMap();
map[ name ] = object;
setMap( map );
};
that.get = function ( name ) {
var map = that.getMap();
return typeof( map[ name ] ) !== "undefined" ? map[name] : null;
};
that.importMap = function ( object ) {
var map = that.getMap();
var key;
for ( key in object ) {
if (object.hasOwnProperty(key)) {
map[key] = object[key];
}
}
setMap(map);
};
that.length = function () {
var map = that.getMap();
var size = 0, key;
for (key in map) {
if (map.hasOwnProperty(key)) size++;
}
return size;
};
that.erase = function () {
localStorage[name] = JSON.stringify({});
};
that.isSet = function (name) {
return that.get(name) != null;
};
that.release = function (name) {
var map = that.getMap();
if (map[name]) {
delete map[name];
}
setMap(map);
};
that.deleteNamespace = function(){
if (localStorage.hasOwnProperty(name)) {
delete localStorage[name];
}
};
return that;
};
LocalMap.destroy = function () {
for ( var item in localStorage ) {
if ( localStorage.hasOwnProperty( item ) ) {
delete localStorage[ item ];
}
}
};
LocalMap.exists = function (name) {
return (localStorage[name]) ? true : false;
};
Below are the unit tests for get and set functions:
test( "Test set()", function() {
var map = LocalMap('test-namespace');
///
map.set("var-1", "val-1");
map.set("var-2", "val-2");
map.set("var-3", "val-3");
//
ok(map.isSet("var-1"), "A variable should be successful set.");
ok(map.isSet("var-2"), "A variable should be successful set.");
ok(map.isSet("var-3"), "A variable should be successful set.");
});
test( "Test get()", function() {
var map = LocalMap('test-namespace');
map.set("var-1", "val-1");
map.set("var-2", "val-2");
map.set("var-3", "val-3");
///
var var1 = map.get("var-1");
var var2 = map.get("var-2");
var var3 = map.get("var-3");
var var4 = map.get("var-4");
//
equal(var1, "val-1", "A set variable should be succesfully retreived.");
equal(var2, "val-2", "A set variable should be succesfully retreived.");
equal(var3, "val-3", "A set variable should be succesfully retreived.");
equal(var4, null, "A variable that was not set should not be retreived.");
});
Hope this helps, and let me know if you have any questions.
How about the below code? I copied it from here. Actually I like its code.
// define dbContext & entities------------------------------------
var DemoDataContext = function () {
nova.data.DbContext.call(this, "Demo", "1.0", "Demo DB", 1000000);
this.users = new nova.data.Repository(this, User, "users");
this.roles = new nova.data.Repository(this, Role, "roles");
};
DemoDataContext.prototype = new nova.data.DbContext();
DemoDataContext.constructor = DemoDataContext;
var User = function () {
nova.data.Entity.call(this);
this.name = "";
this.password = "";
this.birthYear = 1980;
this.createdDate = new Date();
this.deleted = false;
};
User.prototype = new nova.data.Entity();
User.constructor = User;
var Role = function () {
nova.data.Entity.call(this);
this.name = "";
this.createdDate = new Date();
};
Role.prototype = new nova.data.Entity();
Role.constructor = Role;
// end define dbContext & entities------------------------------------
// service methods----------------------------------------------------
function getAllUsers(callback) {
new DemoDataContext().users.toArray(function (users) {
alert(users.length);
callback(users);
});
}
function getUserByName(name, callback) {
new DemoDataContext().users.where("name='" + name + "'").toArray(function (users) {
callback(users.firstOrDefault());
});
}
function addRole(roleName, callback) {
var role = new Role();
role.name = roleName;
var db = new DemoDataContext();
db.roles.add(role);
db.saveChanges(callback);
}
function updateUserPassword(username, password, callback) {
getUserByName(username, function (user) {
if (user == null) {
throw "no user found.";
}
user.password = password;
var db = new DemoDataContext();
db.users.update(user);
db.saveChanges(callback);
});
}
function deleteUserByName(name, callback) {
getUserByName(name, function (user) {
if (user == null) {
throw "no user found.";
}
var db = new DemoDataContext();
db.users.remove(user);
db.saveChanges(callback);
});
}
// end service methods----------------------------------------------------

Categories