Problem with pkg and crypto.generateKeyPairSync - "undefined is not a function" - node.js

I have a problem with the executable generated with pkg using generating RSA keys (crypto.generateKeyPairSync).
I am working on Windows 10 machine with:
node -v: v12.16.3
npm -v: 6.14.4
pkg -v: 4.4.8
The code:
const crypto = require('crypto')
try {
let { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: 'passphrase'
}
});
console.log(publicKey)
console.log(privateKey)
} catch (error) {
console.log(error)
}
The pkg command:
pkg -t node8-win-x64 . --output ./builds/crypto-test.exe
The result (error):
TypeError: undefined is not a function
at Object.<anonymous> (D:\snapshot\crypto-test\index.js:0:0)
at Module._compile (pkg/prelude/bootstrap.js:1320:22)
at Object.Module._extensions..js (module.js:662:10)
at Module.load (module.js:564:32)
at tryModuleLoad (module.js:504:12)
at Function.Module._load (module.js:496:3)
at Function.Module.runMain (pkg/prelude/bootstrap.js:1375:12)
at startup (bootstrap_node.js:240:16)
at bootstrap_node.js:661:3
When I am using the same code without pkg - everything seems to work pefectly:
node .\index.js
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxImzEVPYGwjTwhps1BOh
8vlPMJTEViu7FfYJqYtkkBWXHtn+gAke3x+pe/eVOX2Zxg1qvuw6mYh+2q6UIrl2
MPs8TO5tGXcm7CTsncfp7iqIJZ4OiFl54Ea1eqWSF/wbU7QZRss4+HwqrYKYvtT0
aoIpSzKusgf57msj9Cl+c69M6h4YVENVMBY5t7Xm/jn69x9OytJ2nk+n5Ut8RYZK
+06krjSjsKIlglalBR1hjv+fYSu2pu4qeFD1kuMkwzN85xmv0cbFFWH38sDkyZKS
WB4X0DobwlDIIB0c02ZZmRPJZy0XUeQSM7GgVbIc7mL2aW1PO7Vse/5r0bhIYG9B
I+lf/B7B8iMErTZBxRvY2t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wdkHF0ESMLAZ/Qsc/GjRKEg5
O5VTe1zviWmx0cC0WHa1alz4g+mQNQ3AOjYQBYF5evTrmR04yKEr08hJgCl609kj
xPeYTSeXA0IUe+Xyhn/JVS9jAjOjoba7WE+SCzr98zl01G6vHUTd1M3N23irOXQi
i4yCU8qiSSVEqU5sBdOo7yrIC55i+ozqo0OUNTpmPwC68y52Cg4uSPADReVfFuB3
EQEayu3iMMQs09Mk75b2y94QSxcMca/IJRbJxhomEhLWytRsxu+GPXaX26yi16Dc
VP2282lGDavZlsTjaDMQkt+h7eD6EfxSYoDQEkD/XdMiv7ysgJch6AiyR0M4OR3w
yCD79PxH5/JMiVbwFLHS6Y+/9smOsL2oI7shse/TNZ7VvqLqxrr82oSj5FVcaYph
Oq1UoBi338n5iQEOeedPQZBELpTBqPKhKUqVfb9cDD8HOHgeMU2SZUBMRHp7P63Q
/ia5He9Zm/++7OD9r29yZi7sZ5B6DgOVrHhRJj+AhZJ0
-----END ENCRYPTED PRIVATE KEY-----
Can you guys help me with this issue? I spent hours trying to figure out how to fix this, but with no luck...
Thanks and greetings!

You are using node8-win-x64 in your package. But looks like your development machine is having v12 where it works.
Use v12 in your package.

Related

Exception when using privateEncrypt/privateDecrypt with certain encrypted keys

Steps:
Create an public/private RSA key-pair by using either aes-128-ecb or
aes-128-ocb
Attempt to decrypt/encrypt something
Code:
const crypto = require("crypto");
let {privateKey, publicKey} = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
publicKeyEncoding: {
type: "spki",
format: "pem"
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: "aes-128-ecb",
passphrase: "abcdef"
}
});
const encryptedString = crypto.privateEncrypt({
key: privateKey,
passphrase: "abcdef"
}, Buffer.from("The quick brown fox jumps over the lazy dog")).toString("base64");
const decryptedString = crypto.publicDecrypt(publicKey, Buffer.from(encryptedString, "base64")).toString();
console.log(`Encrypted: ${encryptedString}`);
console.log(`Decrypted: ${decryptedString}`);
I can successfully encryption/decryption with the specified ciphers but it shows following error
node:internal/crypto/cipher:79
return method(data, format, type, passphrase, buffer, padding, oaepHash,
^
Error: error:060CC07A:digital envelope routines:EVP_CIPHER_asn1_to_param:cipher parameter error
at Object.privateEncrypt (node:internal/crypto/cipher:79:12)
at Object.<anonymous> (/home/pancho7532/Documents/AnotherBotXDDXD/rsaTest.js:25:32)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
opensslErrorStack: [
'error:060CC07A:digital envelope routines:EVP_CIPHER_asn1_to_param:cipher parameter error'
],
library: 'digital envelope routines',
function: 'EVP_CIPHER_asn1_to_param',
reason: 'cipher parameter error',
code: 'ERR_OSSL_EVP_CIPHER_PARAMETER_ERROR'
}
It took me a while to work this out, but seems to be an issue with the cipher property. Try using a different cipher.
I tried aes-256-ecb, aes-128-ecb and bf-ecb, none of them worked, then I tried aes-256-cbc, aes-128-cbc and bf-cbc and they all worked. I am not sure why but privateEncrypt() only seems to like all the same ciphers as generateKeyPairSync() does, specifically the "ecb" type.
With some Googling, it seems aes-128-cbc is generally considered better than aes-128-ecb, so maybe that is preferable anyway.

MySQL xdevapi Node Error: SELF_SIGNED_CERT_IN_CHAIN

Windows 10 Pro
MySQL8.0
node.js v14.15.5
openssl 1.1.1c
I'm trying to connect to a MySQL database using node, I'm able to connect without TLS just fine. I used openssl to create a private key and self signed certificate. When I try to use TLS in my node app, I keep getting the following error:
$ NODE_TLS_REJECT_UNAUTHORIZED=0 node index.js
(node:15480) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
(Use `node --trace-warnings ...` to show where the warning was created)
Error: self signed certificate in certificate chain
at TLSSocket.onConnectSecure (_tls_wrap.js:1497:34)
at TLSSocket.emit (events.js:315:20)
at TLSSocket._finishInit (_tls_wrap.js:932:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:706:12) {
code: 'SELF_SIGNED_CERT_IN_CHAIN'
}
TypeError: Cannot read property 'sql' of undefined
at C:\Users\gregb\Desktop\PROGRAMMING\VS Code Workspace\xdevapi2\index.js:40:32
at processTicksAndRejections (internal/process/task_queues.js:93:5)
[]
[]
Index.js
let mysqlx = require('#mysql/xdevapi');
let fs = require('fs');
require('dotenv').config();
let rows = [];
let columns = [];
// Works without TLS
// let config = {
// host: 'localhost',
// port: 33060,
// user: 'root',
// database: 'user',
// password: process.env.password
// };
const config = {
host: 'localhost',
port: 33060,
user: 'root',
database: 'user',
password: process.env.password,
ssl: true,
tls: {
rejectUnauthorized: false,
key: fs.readFileSync('./privatekey2.pem'),
cert: fs.readFileSync('./example.crt'),
ca: './cacert.pem'
}
};
(async function () {
let session;
try {
session = await mysqlx.getSession(config);
} catch(err) {
console.log(err);
}
try {
let result = await session.sql('SELECT "firstName" AS c1, "lastName" AS c2')
.execute(row => rows.push(row), column => columns = columns.concat(column));
session.close();
} catch(err) {
console.log(err);
}
console.log(rows); // [['foo', 'bar']]
console.log(columns.map(column => column.getColumnLabel())); // ['c1', 'c2']
})();
I also tried:
NODE_TLS_REJECT_UNAUTHORIZED='0' node index.js
How I used openssl:
Create a public/private key file pair:
openssl genrsa -out privkey2.pem 4096
Split into public/private:
openssl ssh-keygen -t rsa -b 4096 -f privatekey2.pem
Create a cert
openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes -keyout privatekey2.pem -out example.crt
The problem does not seem to be related to the certificate you are using. It should be related to the fact that you provide a path for the certificate authority file (ca). You do this when you want the client to verify that the server certificate was signed using a certificate in the CA chain, which only works if rejectUnauthorized is true, which is automatically set once you provide that valid CA file path, thus, your custom rejectUnauthorized: false is ignored.
Which begs the question, Is the server certificate signed by the CA you are providing? I suspect it is not, in which case, the error is legitimate.
If so, then it is a bug, and you should report it using the public MySQL issue tracker. However, I ran a few tests and I'm convinced there is no issue, but if you are able to produce a server certificate that was, indeed, signed by that particular CA, which allows to reproduce the same exact scenario, maybe we can dig some dirt.
Disclaimer: I'm the lead developer of MySQL X DevAPI Connector for Node.js

Facebook SDK on Linux Unity Editor cant found Keytool

I working on Pop_OS 20.04 LTS with Unity 2019.4 LTS and I have problem, Facebook SDK cant found Keytool. In source code available on GitHub sdk trying to execute next command:
keytool -exportcert -alias androiddebugkey -keystore debug.keystore | openssl sha1 -binary | openssl base64
I can execute it from terminal or even from c# program using their code from sdk, but in unity this not working for some reason:
static void Main(string[] args)
{
var proc = new Process();
var arguments = #"""keytool -storepass {0} -keypass {1} -exportcert -alias {2} -keystore {3} | openssl sha1 -binary | openssl base64""";
proc.StartInfo.FileName = "bash";
arguments = #"-c " + arguments;
proc.StartInfo.Arguments = string.Format(arguments, "android", "android", "androiddebugkey", System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + #"/.android/debug.keystore");
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
var keyHash = new StringBuilder();
while (!proc.HasExited)
{
keyHash.Append(proc.StandardOutput.ReadToEnd());
}
switch (proc.ExitCode)
{
case 255: Console.WriteLine("Error");
return;
}
Console.WriteLine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + #"/.android/debug.keystore");
Console.WriteLine(keyHash.ToString());
}
. Can somebody help with this?
It looks like I can safely use the hash generated by this command.
keytool -exportcert -alias androiddebugkey -keystore debug.keystore | openssl sha1 -binary | openssl base64
Although I get an error stating that Facebook is not configured,but it does not prevent me from building a workable application

SSL, Express, Nodejs: Error: error:0909006C:PEM routines:get_name:no start line

i tried to add certificates to my nodeJs, Express server like this:
cert: fs.readFileSync('/path/to/private.key'),
key: fs.readFileSync('/path/to/your_domain_name.crt'),
ca: [
fs.readFileSync('path/to/CA_root.crt'),
fs.readFileSync('path/to/ca_bundle_certificate.crt')
]
and i got this error
c.context.setKey(key, passphrase);
^
Error: error:0909006C:PEM routines:get_name:no start line
at Object.createSecureContext (_tls_common.js:151:17)
at Server.setSecureContext (_tls_wrap.js:1155:27)
at Server (_tls_wrap.js:1033:8)
at new Server (https.js:65:14)
at Object.createServer (https.js:89:10)
at Object.<anonymous> (********)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11 {
library: 'PEM routines',
function: 'get_name',
reason: 'no start line',
code: 'ERR_OSSL_PEM_NO_START_LINE'
}
does anyone faced this problem please?
Thanks by advance
Your may write wrong file name in cert and key section.
key: section need private key filename and cert: section need certification filename.
I switched your filename in cert and key section.
cert: fs.readFileSync('/path/to/your_domain_name.crt'),
key: fs.readFileSync('/path/to/private.key'),
ca: [
fs.readFileSync('path/to/CA_root.crt'),
fs.readFileSync('path/to/ca_bundle_certificate.crt')
]

".then is not a function" from a very simple inquirer program

the very simple example below (pretty much copied off the npm inquirer front page) is giving the ".then is not a function" error. However I can't figure out what the issue is.
var inquirer = require('inquirer');
inquirer.prompt([
{
name: 'my_name',
type: 'input',
message: 'What is your name: '
}]).then(answers => {
console.log("Your name is:"+answers.my_name)
});
The error message looks like this:
? What is your name:
/home/peter/Documents/nodejs.d/vscode_examples_workspace/security/inq.js:8
}]).then(answers => {
^
TypeError: inquirer.prompt(...).then is not a function
at Object.<anonymous> (/home/peter/Documents/nodejs.d/vscode_examples_workspace/security/inq.js:8:13)
at Module._compile (internal/modules/cjs/loader.js:654:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
at Module.load (internal/modules/cjs/loader.js:566:32)
at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
at Function.Module._load (internal/modules/cjs/loader.js:498:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:695:10)
at startup (internal/bootstrap/node.js:201:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:516:3)
But the following example works OK. So the basic node.js environment (nodejs --version = v9.11.2) is OK.
var inquirer = require('inquirer');
let q = [
{
name: 'my_name',
type: 'input',
message: 'What is your name: '
}];
inquirer.prompt (q, function (answers){
console.log("Your name is: "+answers.my_name);
});
// Output
$ nodejs inq.js
? What is your name: Peter
Your name is: Peter
This is probably because you have an old version of inquirer (0.12.0 or older) which does not support promises (promises were added in version 1.0.0).
Your snippet works fine with version 6.0.0 and 1.0.0 but fails with the exact same error message in version 0.12.0.
Check packages.json for your version and update it:
"dependencies": {
"inquirer": "^6.0.0"
}
Then do
npm install

Resources