Python Javascript CryptoJS - javascript

I am looking for a module that I can use in both python & javascript so that can encrypt something in python then decrypt in javascript if I pass in a key (and vice versa).
So far I've checked out SlowAES and CryptoJS, but cant find any good documentation or examples. Is anyone able to help?
Below is my attempt to get this working:
JS:
var encoded_message = 'MTAxMTEyMTMxNDE1MTYxN2asfw3LtCtoL+mvWtJsIVSVCsvZdBIvZWWRuKEI85nd';
var my_iv = CryptoJS.enc.Base64.parse('1011121314151617');
var my_key = CryptoJS.enc.Base64.parse('824601be6c2941fabe7fe256d4d5a2b7');
console.log('my iv [' + my_iv + ']');
console.log('my key [' + my_key + ']');
console.log('my enc message [' + encoded_message + ']');
var data = CryptoJS.AES.decrypt(encoded_message, my_key, { iv: my_iv, mode: CryptoJS.mode.CBC });
console.log(data);
var dec = CryptoJS.enc.Hex.stringify(data);
console.log('data [' + dec + ']');
var encoded_message = CryptoJS.enc.Base64.parse('MTAxMTEyMTMxNDE1MTYxN2asfw3LtCtoL+mvWtJsIVSVCsvZdBIvZWWRuKEI85nd');
console.log('\n\n\n');
console.log('message [' + encoded_message + ']');
Python:
import os, random, struct
from Crypto.Cipher import AES
from Crypto import Random
import base64
class AESCipher:
def __init__(self, key):
BS = 16
self.pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
self.unpad = lambda s : s[0:-ord(s[-1])]
self.key = self.pad(key[0:16])
def encrypt(self, raw):
raw = self.pad(raw)
iv = "1011121314151617"
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw))
def decrypt(self, enc):
enc = enc.replace(' ', '+')
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return self.unpad(cipher.decrypt(enc[16:]))
def main():
message = 'this is my new message'
print message[:16]
cipher = AESCipher('824601be6c2941fabe7fe256d4d5a2b7')
encrypteddata = cipher.encrypt('work you bloody thing!')
print encrypteddata
decryptdata =cipher.decrypt(encrypteddata)
print decryptdata
main()

I've recently been using sjcl in Javascript,..
http://bitwiseshiftleft.github.io/sjcl/
They also appears to be a python compatible version.
https://pypi.python.org/pypi/sjcl
At it's simplest you can just do ->
sjcl.encrypt("password", "data")
and
sjcl.decrypt("password", "encrypted-data")
But you still can do low level stuff with it too.

Related

Check if UUID is included in pastebin

I would like for to check if my UUID is includedin my pastebin.
Any idea how I can check that in JavaScript?
The code to actually get the UUID is this:
// GET UUID
const execSync = require("child_process").execSync;
const { type } = require("os");
const { SSL_OP_EPHEMERAL_RSA } = require("constants");
let response = execSync("wmic csproduct get uuid");
let serial = String(response).split("\n")[1];
console.log(serial);
async function fetchText() {
let response = await fetch("https://pastebin.com/raw/4hxgLxyd");
let data = await response.text();
console.log(data.indexOf(serial));
if (data.indexOf(serial) !== -1) {
console.log("included");
} else {
console.log("not included");
}
}
fetchText();
I am new to JS - in Python I know how to check it with a request command.
Anyone knows how to handle this in JS maybe?
As requested my Python code:
def init(): # check HWID
try:
HWID = subprocess.check_output('wmic csproduct get uuid').decode().split('\n')[1].strip()
except:
cmd = "system_profiler SPHardwareDataType | grep 'Serial Number' | awk '{print $4}'"
result = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True, check=True)
HWID = result.stdout.decode().strip()
print('Checking license...')
# -------------------------------------------
# Below this - I need the code for JavaScript
# -------------------------------------------
r = requests.get('https://pastebin.com/xxx')
try:
if HWID in r.text:
pass
else:
print('[ERROR] HWID not registered!')
print(f'HWID: {HWID}')
time.sleep(5)
sys.exit(0)
except:
print('[ERROR] Failed to initiate')
time.sleep(5)
sys.exit(0)
print(f'HWID: {HWID}')
print('--- License is valid ---')
In javascript, you can use indexOf to search for the occurrence of a string. The function will return -1 if it does not exist, otherwise the index the first occurrence.
Additionally, make sure you account for things like case sensitivity and placement of dashes and whitespace.
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
See the Node.Js documentation for performing the http request.
// GET UUID
const execSync = require("child_process").execSync;
const response = execSync("wmic csproduct get uuid");
const serial = String(response).split("\n")[1].replace("-", "").trim().toLowerCase();
const https = require('https')
const options = {
hostname: 'pastebin.com',
port: 443,
path: '/xxx',
method: 'GET'
}
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
var dnorm= d.replace("-", "").trim().toLowerCase();
process.stdout.write(dnorm.indexOf(serial))
})
})
req.on('error', error => {
console.error(error)
})
req.end()
Since it appears you are having a whitespace or encoding issue, please manually compare the contents of the string:
function debugComp(a, b)
{
a= a.toString().trim();
b= a.toString().trim();
console.log("a: '" + a + "' - Length: " + a.length);
console.log("b: '" + b + "' - Length: " + b.length);
if(a.indexOf(b)>-1)
{
console.log("Found at index " + a.indexOf(b));
}
else if(a.length==b.length)
{
for(var i=0; i< a.length; i++)
{
console.log("a[" + i + "]= '" + a[i] + "' - b[" + i + "] = '" + b[i]);
console.log("a[" + i + "] == b[" + i+ "] = " + (a[i]==b[i]));
}
}
else {
console.log("Strings have different lengths");
}
}
debugComp("D340D9AE-A43F-DF47-AFED-A93222AB3646", "D340D9AE-A43F-DF47-AFED-A93222AB3646");

Node.js encrypting and decrypting is doubling file size

I am creating a Node.js application that can encrypt and decrypt image files. However when my code is run I get varying results: Sometimes the decrypted image looks like the original at the top but the bottom half looks corrupted, sometimes the decrypted image is completely there but looks like it was heavily compressed and sometimes the decrypted image is too corrupt to open. Here is an image that demonstrates this. The only thing these results have in common is the encrypted and decrypted images are double the file size of the original image.
const fs = require('fs');
const crypto = require('crypto');
var path = 'C:\\Users\\' + windowsUserName + '\\Desktop\\image';
var fileExtension = '.jpg';
var password = '1234';
var algorithm = 'aes-256-cbc';
var image = fs.createReadStream(path + fileExtension);
var encryptedImage = fs.createWriteStream(path + ' encrypted' + fileExtension);
var decryptedImage = fs.createWriteStream(path + ' decrypted' + fileExtension);
var encrypt = crypto.createCipher(algorithm, password);
var decrypt = crypto.createDecipher(algorithm, password);
image.pipe(encrypt).pipe(encryptedImage);
image.pipe(encrypt).pipe(decrypt).pipe(decryptedImage);
How do I fix the image corruption and file size doubling?
You are trying to decrypt the cypher before it is finished. If you wait until the pipe is done and read the encrypted file, it should not be garbled:
const fs = require('fs');
const crypto = require('crypto');
var path = 'file path';
var fileExtension = '.jpg';
var password = '1234';
var algorithm = 'aes-256-cbc';
var image = fs.createReadStream(path + fileExtension);
var encryptedImage = fs.createWriteStream(path + ' encrypted' + fileExtension);
var encrypt = crypto.createCipher(algorithm, password);
image.pipe(encrypt).pipe(encryptedImage);
encryptedImage.on("finish", function(){
var decrypt = crypto.createDecipher(algorithm, password);
var decryptedImage = fs.createWriteStream(path + ' decrypted' + fileExtension);
var encryptedImage = fs.createReadStream(path + ' encrypted' + fileExtension);
encryptedImage.pipe(decrypt).pipe(decryptedImage);
})

How to Generate and validate JWE in node js?

I tried the bellow code to create RSA-OAEP and A128GCM JWE generator and validator. it works with node js , ie, encrypt claims and generate the jwe and decrypt the same gives me the claims. but it is not working with the other clients , like nimbusds jose, jose4j. So for a sure I am missing something.
I am doing this by reading https://www.rfc-editor.org/rfc/rfc7516
index.js
var crypto = require('crypto');
var randomstring = require("randomstring");
var ursa = require("ursa");
var fs = require("fs");
var base64url = require('base64url');
var ascii = require("./ASCII");
var claims = {
firstName: "vimal"
};
var header = {
"enc": "A128GCM",
"alg": "RSA-OAEP"
};
var headerBase64Url = base64url.encode(JSON.stringify(header));
console.log("headerBase64Url : " + headerBase64Url);
console.log("headerBase64Url to UTF8 : " + base64url.decode(headerBase64Url));
var cek = randomstring.generate(16);
console.log("cek : " + cek);
var publicKey = ursa.createPublicKey(fs.readFileSync('./pubkey.pem'));
var encryptedKey = publicKey.encrypt(cek, 'utf8', 'base64');
console.log("encryptedKey : " + encryptedKey);
// var privateKey = ursa.createPrivateKey(fs.readFileSync('./privkey.pkc8.pem'));
// var decryptedKey = privateKey.decrypt(encryptedKey, "hex", "utf8");
// console.log("decryptedKey : " + decryptedKey);
var iv = randomstring.generate(12);
console.log("IV : " + iv);
var cipher = crypto.createCipheriv('aes-128-gcm', cek, iv);
cipher.setAAD(Buffer.from(ascii.toASCII(headerBase64Url)));
var chipherText = cipher.update(JSON.stringify(claims), "utf8", "base64");
chipherText += cipher.final('base64');
console.log("chipherText : " + chipherText);
var chipherTextAuthTag = cipher.getAuthTag().toString("base64");
console.log("chipherText Auth Tag : " + chipherTextAuthTag);
var jweToken = headerBase64Url + "." + base64url.encode(encryptedKey, "base64") + "." + base64url.encode(iv, "base64") + "." + base64url.encode(chipherText, "base64") +
"." + base64url.encode(chipherTextAuthTag, "base64");
console.log("jweToken : " + jweToken);
// decrypt
var jweTokenParts = jweToken.split(".");
var headerHex = base64url.decode(jweTokenParts[0]);
console.log(headerHex);
var encryptedKeyHex = base64url.decode(jweTokenParts[1], "base64");
console.log(encryptedKeyHex);
var ivHex = base64url.decode(jweTokenParts[2], "base64");
console.log(ivHex);
var chipperTextHex = base64url.decode(jweTokenParts[3], "base64");
console.log(chipperTextHex);
var chipherTextAuthTagHex = base64url.decode(jweTokenParts[4], "base64");
console.log(chipherTextAuthTagHex);
var privateKey = ursa.createPrivateKey(fs.readFileSync('./privkey.pkc8.pem'));
var decryptedKeyHex = privateKey.decrypt(encryptedKeyHex, "base64", "utf8");
console.log("decryptedKeyHex : " + decryptedKeyHex);
var dcipher = crypto.createDecipheriv('aes-128-gcm', decryptedKeyHex, iv);
dcipher.setAAD(Buffer.from(ascii.toASCII(jweTokenParts[0])));
dcipher.setAuthTag(Buffer.from(chipherTextAuthTagHex, "base64"));
var planText = dcipher.update(chipperTextHex, "base64", "utf8");
planText += dcipher.final('utf8');
console.log(planText);
ASCII.js
function toASCII(text) {
var ascii = "";
for (var f in text) {
ascii = ascii + text.charCodeAt(f);
}
return ascii;
}
module.exports = {
toASCII: toASCII
};
Generated public and private key using the below command
openssl genrsa -out ./privkey.pem 2048
openssl pkcs8 -topk8 -inform pem -in ./privkey.pem -outform pem -nocrypt -out ./privkey.pkc8.pem
openssl rsa -in ./privkey.pkc8.pem -pubout -out ./pubkey.pem
Please help me to fix this code.
This is my public key
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyT0HZHrlk8nN8HfTDq5t
dv6UCKHf7+RF1bICxaR4h2vzGCqcYUlzyW7Sp33BZAHDeO3d5tX26m7z2EOPaOPn
SSe6psgvBmE4Ivyc3+uyIYJm+Eo9bXiqqfvuDRidXsHj23w41l6GMERKbpOBVvp+
dmWt/cWU8FESvKUqNw/Au2R9mE1sQ5irMQj42hhUrVA1azs2AYpysKNZABm11YMb
/vd/xSPLsNqcDefuCs7j3CcT9xNLrMV6K63QjCAP+h0IMuA+ayi3WRUbl04D6cAC
AC97/cKMC0YLRumbf5x5/KjUBwNlzgRA3/n9KE+YjJ9Rs9dtiGnlg+c70Kgx4hm9
9QIDAQAB
-----END PUBLIC KEY-----
Generated JWE
eyJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.A_KMJqfr6FZSoejRGWPsZKMCNZmPyaWoNvpG6KMRpqyv7Alb8Ui5ELWLjpcaemjNM8EFU8d4-Yzz8jRRZ5TpK2pEEc4NXfDLcnj2b0-38_-P-0HbW1YyMkkGMVXIpJDYMo8vKgVHIBj0pNlzgF7xmxLFWZlJlXmYzXi4QZcig5HezHg7AAQB7U2HYry25cQDYam60747gRCH372NaSm_dfRCNvH8copVXqiJGNs6xhslxMt_LopnZt9iIcAC9o7m0FPdnu_0Ui_w0jp5OUam8i0v8k6SSajBvXSedtUENxcehPGRSFYzi8KqZ53u4CpRygir84wNFRTi7zmLV6TlVw.84xgyx6TTI8I.4zTt1fI1XCbvxW2L-pH8_Mfp_ySF.EPmpEHiMYAvA2nqz9M0v5Q
It looks like the IV is not correctly encoded using Base64 Url.
On my computer, when I execute the following line of code:
console.log(iv);
console.log(base64url.encode(iv, "base64"));
Then the two lines are identical.
When I modify your code:
var jweToken = headerBase64Url + "." + base64url.encode(encryptedKey, "base64") + "." + base64url.encode(iv, "base64") + "." + base64url.encode(chipherText, "base64") +
"." + base64url.encode(chipherTextAuthTag, "base64");
lnto these lines:
var bufferedIV = new Buffer(iv);
var jweToken = headerBase64Url + "." + base64url.encode(encryptedKey, "base64") + "." + base64url.encode(bufferedIV, "base64") + "." + base64url.encode(chipherText, "base64") +
"." + base64url.encode(chipherTextAuthTag, "base64");
Then it works fine ; I can load the resulting JWE using my PHP library.
From my understanding, the error comes from the base64url dependency that does not correctly encode the IV.

calculate md5 of image loaded in java webdriver

I want calculate md5 of images that loaded in webdriver in java.
webdriver is Firefox.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.JavascriptExecutor;
String script = "var imgElement = document.querySelector('div.mtl:nth-child(2) > div:nth-child(1) > img:nth-child(1))'; *** return md5 of image *** ";
String url = "http://www.facebook.com";
WebDriver webDriver = new FirefoxDriver();
driver.get(url);
JavascriptExecutor js = (JavascriptExecutor) driver;
Stgin md5 = (String) js.executeScript(script);
in this code, what must replace with :
*** return md5 of image ***
You can use fetch with force-cache to get the content from cache. Then digest the arrayBuffer from the response. Unfortunately, MD5 is too old and the browser doesn't support it anymore. See more details about Crypto here. You can choose SHA-1, SHA-256, SHA-384, and SHA-512. See an example to digest SHA-256 below.
public void getImageSHA256(){
driver.get("https://www.blognone.com/");
WebElement img = driver.findElement(By.cssSelector("img"));
String imgUrl = img.getAttribute("src").trim();
String script = "function hex(buffer) { var hexCodes = []; var view = new DataView(buffer); for (var i = 0; i < view.byteLength; i += 4) { var value = view.getUint32(i); var stringValue = value.toString(16); var padding = '00000000'; var paddedValue = (padding + stringValue).slice(-padding.length); hexCodes.push(paddedValue); } return hexCodes.join(\"\");}" +
"var callback = arguments[arguments.length - 1];" +
"fetch(arguments[0],{cache:'force-cache'}).then((response)=> {" +
"return response.arrayBuffer(); }).then((buffer)=>{" +
" return crypto.subtle.digest('SHA-256', buffer); }).then((hashArray)=>{" +
" callback(hex(hashArray));"+
"});";
driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);
Object response = ((JavascriptExecutor) driver).executeAsyncScript(script, imgUrl);
System.out.println(response);
}
Screenshot below show comparison between SHA-256 from my code and SHA-256 from an online tool.
public void getImageMD5(){
driver.get("https://www.blognone.com/");
WebElement img = driver.findElement(By.cssSelector("img"));
String imgUrl = img.getAttribute("src").trim();
String script = "var callback = arguments[arguments.length - 1];"
+ "function _arrayBufferToBase64( buffer ) {"
+ " var binary = '';"
+ " var bytes = new Uint8Array( buffer );"
+ " var len = bytes.byteLength;"
+ " for (var i = 0; i < len; i++) {"
+ " binary += String.fromCharCode( bytes[ i ] );"
+ " }"
+ " return window.btoa( binary );"
+ "}"
+ " fetch(' " + imgUrl + " ',{cache:'force-cache'})."
+ "then((response)=>{return response.arrayBuffer()})."
+ "then((response)=>{return _arrayBufferToBase64(response)})."
+ "then((response)=>{callback(response)});";
driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);
Object response = ((JavascriptExecutor) driver).executeAsyncScript(script, imgUrl);
byte[] data = Base64.getDecoder().decode((String) response);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(data);
StringBuilder sb = new StringBuilder(2 * hash.length);
for (byte b : hash) {
sb.append(String.format("%02x", b & 0xff));
}
String digest = sb.toString();
System.out.println("MD5 of Image : " + digest);
}

SyntaxError: Unexpected token V

I know this is a commonly asked question but I need to know theory wise, why this is happening?
I am trying to parse two encrypted values to my service.
Javascript
var encryptedlogin = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(Email), key,
{
keySize: 128 / 8,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var encryptedpassword = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(PasswordTwo), key,
{
keySize: 128 / 8,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var c = String(encryptedlogin);
var d = String(encryptedpassword);
var json = JSON.parse(c);
var json1 = JSON.parse(d);
$http.get("http://localhost:53101/TruckService.svc/validateUserA/" + json + '|' + json1 )
.success(function(data) {});
.error(function(data) {});
Try this:
var json = JSON.parse('"' + c + '"');
var json1 = JSON.parse('"' + d + '"');
JSON strings must be in double quotes
Why do you need to turn it into JSON?
By the look of your get request, you could just do:
$http.get("http://localhost:53101/TruckService.svc/validateUserA/" + encodeURIComponent(c + '|' + d))
.success(function(data) {});
.error(function(data) {});
Or your url may be in the format of
"http://localhost:53101/TruckService.svc/validateUserA/?parameterName=" + encodeURIComponent(c + '|' + d)
try to use
'/' instead of '|'
$http.get("http://localhost:53101/TruckService.svc/validateUserA/" + json + '/' + json1 )

Categories