I am using KARATE with the standalone JAR, version 0.9.5.RC5.
Inside a Karate scenario, I have to sign a string with a private key, using the SHA256 with ECDSA algorithm, in base64.
I need this signature further in a request.
So, I have written in the scenario :
* def stringtobesigned = 'mystringtosign'
* def privkey = 'DeIHYzu9...'
* def Signature = call read('sha256ECDSA.js')
And in the sha256ECDSA.js file, I have written :
function fn() {
var mykey = karate.get('privkey');
var strToBeSigned = karate.get('idstring2signed');
...
return signValue;
}
Can anybody tell me how to implement this algorithm in my use case?
I need to replace '...' with the right code, to the value 'signValue'.
Thanks a lot.
Related
I was developing python program with Eel module.
But there is problem. It's that return null from eel.getImgSrc(path) function to get image's byte data.
Look at this code.
-----web/main.js------
async function run(path) {
let n = await eel.getImgSrc(path)() //path is correct. but n is null.
console.log(n);
}
-----app.py------
#eel.expose
def getImgSrc(path):
f = open(path, 'rb')
return f.read()
In Eel, the Python and JavaScript layers communicate by passing JSON back-and-forth. Internally, the Python side is passing your Python return value through a function that's defined like this: jsn.dumps(obj, default=lambda o: None) which results in the string null in your case. You can confirm this behavior by updating your code for debugging purposes only to something like this:
#eel.expose
def getImgSrc(path):
f = open(path, 'rb')
data = f.read()
print(json.dumps(data, default=lambda o: None))
return data
You'll see it prints out null. That's why you're seeing null on the JavaScript side.
I'm not a developer on the Eel project, so I can't explain the rationale of why this happens (I just see it in the source code). But now that you know it's happening, you can solve the problem by finding a way to encode your data so that it can be passed via JSON. (And you can use the sample code I posted above to check that it gets encoded properly.)
A search on the web for how to encode binary data into JSON with Python and decode with JavaScript will yield many results... so pick one that suits your particular needs. One way that's common (and is discussed in an issue on the Eel project website), is to base64 encode the data on the Python side and then decode it on the JavaScript side. It's not ideal, but is a workable solution that I've used in the past. Your code would be something like this...
-----web/main.js------
async function run(path) {
let n = await eel.getImgSrc(path)() // should no longer be null
console.log(atob(n));
}
-----app.py------
#eel.expose
def getImgSrc(path):
f = open(path, 'rb')
data = f.read()
data = base64.b64encode(data).decode("utf-8")
return data
Additionally, HTML image tags can accept base64 encoded data, so you could do something like:
async function run(path) {
let n = await eel.getImgSrc(path)() // should no longer be null
let imageEl = document.getElementById('image');
imageEl.src = "data:image/jpeg;base64," + n;
// any other processing...
}
You will probably need to tweak these examples to fit your exact needs.
I am trying to run the script in jmeter but do not know how to handle the AES 256 encryption used for password. Help appreciated.
You can perform whatever encoding operations you want using JSR223 Test Elements and Groovy language via Java Cryptography API, example code for AES 256 encryption would be something like:
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
def textToEncrypt = 'foo'
def secret = 'xxxxxxxxxxxxxxxx'
def cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE")
def key = new SecretKeySpec(secret.getBytes("UTF-8"), "AES")
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(secret.getBytes("UTF-8")))
vars.put('encrypted', cipher.doFinal(textToEncrypt.getBytes("UTF-8")).encodeBase64() as String)
Demo:
I've faced with following issue: i try to convert some string str to md5 bytestring hash. In PHP we can use md5(str, true), but in JS (nodejs express) i can't find some way to receive the same result. I've included npm module js-md5, but arrayBuffer method of this module returns another result (differes from PHP md5(str, true)).
Could somebody help me, please.
Thanks
var md5 = require('md5');
console.log(md5('text'))
Use CryptoJS module :
NPM link here
And do something like :
// Requires
var crypto = require('crypto');
// Constructor
function Crypto() {
this.hash;
}
// Hash method
Crypto.prototype.encode = function(data) {
this.hash = crypto.createHash('md5').update(data);
var result = this.hash.digest('hex');
return result;
};
// Comparison method (return true if === else false)
Crypto.prototype.equals = function(data, model) {
var bool = false;
var data = data.toUpperCase();
var model = String(model).toUpperCase();
if (data == model){
bool = true;
} else {
bool = false;
}
return bool;
};
// Exports
module.exports = Crypto;
Then instantiate this "tool" object in your code and use methods.
Easy as pie, and the same thing can be done with anothers encryption methods like AES, SHA256, etc.
About the raw_output option (binary answer, padded on 16 bits) you can easily convert the returned var in binary format with a simple function, see this SO post to know how.
Have fun.
Short answer:
const crypto = require('crypto');
const buffer = crypto.createHash('md5').update(str).digest();
Long answer: you need to use NodeJS’ default crypto module (no need for a dependency here), which contains utility function and classes. It is able to create hashes (for instance MD5 or SHA-1 hashes) for you using synchronous or asynchronous methods. A short utility function named crypto.createHash(algorithm) is useful to create a hash with minimal coding. As the docs specifies:
The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. On recent releases of OpenSSL, openssl list-message-digest-algorithms will display the available digest algorithms.
Now, this createHash function returns a Hash object, which can be used with a stream (you can feed it a file, HTTP request, etc.) or a string, as you asked. If you want to use a string, use hash.update(string) to hash it. This method returns the hash itself, so you can chain it with .digest(encoding) to generate a string (if encoding is set) or a Buffer (if it’s not). Since you asked for bytes, I believe a Buffer is what you want (Buffers are Uint8Array instances).
Facing an issue while creating SHA1 from javascript and java. The problem is both are different. It is used for validating the client request to web server. That means client send a based64 encoded security key to server and server regenerate the same key and equate both are same. Please find below code for generating secret keys in client and server.
Server
MessageDigest mDigest = null;
try {
mDigest = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
String input = value1 + value1 + server_key;
byte[] result = mDigest.digest(input.getBytes());
String secret = Base64.encodeToString(result, Base64.NO_WRAP);
...
//comparison logic goes here
...
Client (java script)
var input = value1 + value2 + server_key;
//http://code.google.com/p/crypto-js/
var hash = CryptoJS.SHA1(input);
var encoded = base64Encode(hash.toString());
//WEB SERVICE INVOCATION FROM JAVASCRIPT GIES HERE.
The values value1, value1, server_key will be available in both client and server. The issue we are facing is, the SHA1 generated in both client and server is not matching. I understand the issue is in java its using getBytes() and in javascript using string value for generating SHA1. The CryptoJS.SHA1 does not support bytearray as parameter. We cannot change the server code as it is used by many client applications. Any help will be much appreciated.
In Java ->
byte[] result = mDigest.digest(input.getBytes());
and in JavaScript ->
var hash = CryptoJS.SHA1(input);.
I belief this is the problem. In java the parameter is a bytearray and output is also a bytearray. But in javascript the parameter is var (string) and return is also var (string). I 've also compared the output of CryptoJS.SHA1 with some online SHA1 generating tools. The comparison is true. I am not an expert in this area. If you can explain more, it will be more helpful.
I managed it to do in another way. My application is a cordova based application. So generated the sha1 and encoded it from java and objC and invoked it using cordova plugins.
I am struggling with SHA256 encoding.
There is a Python example but I don't understand it quite well.
Example (Python):
message = nonce + client_id + api_key
signature = hmac.new(API_SECRET, msg=message, digestmod=hashlib.sha256).hexdigest().upper()
Can somebody make a simple blueprint so I can work from there?
Crypto-js implements SHA256
If you include the library, you should be able to run the following (assuming 'message' and 'API_SECRET' are the same as the python code)
var signature = CryptoJS.HmacSHA256(message,API_SECRET).toString(CryptoJS.enc.Hex).toUpperCase();