Connect to an SFTP server - node.js

I am trying to setup a SFTP server on AWS.
I am using ssh2-sftp-client as a client to connect to my server on AWS.
I have tried this before connecting to a local server and was working successfully, the only difference now is that I am trying to use a ppk instead of a password.
I used PuttyGen to convert my pub-key into a ppk but still doesn't like it.
This is what my connection looks like:
await sftp.connect({
host: process.env.SFTP_HOST,
port: process.env.SFTP_PORT,
username: process.env.SFTP_USERNAME,
privateKey: fs.readFileSync('./transfer_key.ppk')
})
and this is the error I get:
Error: ENOENT: no such file or directory, open './transfer_key.ppk'
Any idea how to connect to AWS transfer in this way?
Thank you

The error message implies it cant find the file, but maybe it means it cant find a valid file? I think your issue could be the .ppk file created by PuttyGen is the wrong kind of key file. The client is expecting a private key in "OpenSSH format", ppk files are only used with Windows applications like putty/pageant/winscp afaik.
Try loading your .ppk into puttygen, make sure the password is set and then use the Conversions menu --> Export OpenSSH key option. This creates a new text file that contains a header line, your encoded private key and a footer that would look something like this (only longer) if viewed in a text editor:
-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBDIKCAQEAmnsdLEsp2hkdz+kVoCuL6JYiu5t/jUZCeaQc8TRyEeLUsk2H
0wMA8azMyzt+a1JcNa2j+jrE5Fd6UiJ7do6OQFgqLxv48QCpwNximS20yavKNCGs
5HCsP4feVq2/2/IaCMNLEcv2XBweipYyY0ME+w1wSojWwCetMw==
-----END RSA PRIVATE KEY-----

Related

HTTPS in Nodejs - error:06065064 digital envelope routines evp_decryptfinal_ex bad decrypt

We tried to install our Hapis (Nodejs Version 14) Web service on our customer's server. It ran under HTTP for months, but when we went to enable HTTPS with the appropriate paths to the cert and key it fails when the service starts up with:
error:06065064:digital envelope routines:EVP_Decryptfinal_ex:bad decrypt
Their certificate and key are generated using the Venafi online portal. It gave them a crt and key. The crt uses a Signature algorithm: sha256RSA, Signature hash algorithm of sha256, and Thumbprint algorith: sha1.
Also, the private key is a RSA PRIVATE KEY with Proc-Type: 4,ENCRYPTED and DEK-Info: DES-EDE3-CBC.
I am not sure what is going on, because HTTPS works fine on our development servers.
Is the problem in HapiJS?
Is the problem with the certificate or key themselves?
Is there an Node option I need to be passing in when creating the service?
Please help.
The specified error 06065064:digital envelope routines:EVP_Decryptfinal_ex:bad decrypt occurs in an SSL/TLS connection using OpenSSL (which is what nodejs modules like tls and https actually use) when the privatekey is encrypted (with a passphrase) and the correct passphrase is not provided to decrypt it. The described file format, beginning with a line -----BEGIN RSA PRIVATE KEY----- followed by lines Proc-Type: and DEK-Info: is indeed one of the encrypted formats used by OpenSSL. Specifically this is the encrypted 'traditional' or 'legacy' format; the PKSC8 format added about 2000 but still considered new(!) uses -----BEGIN ENCRYPTED PRIVATE KEY----- and no 822-style headers, only base64 (of the encrypted structure defined by PKCS8); see ursinely-verbose https://security.stackexchange.com/questions/39279/stronger-encryption-for-ssh-keys/#52564 about OpenSSH's use of OpenSSL, which is basically the same as nodejs's use.
The tls module and others that build on it including https ultimately read the key(s) and cert(s) using tls.createSecureContext which accepts in options a member passphrase, or if you need to use multiple keys (and certs) you can provide a passphrase for each key as described in the linked doc.
Alternatively you can avoid the need for a passphrase by converting the key to an unencrypted file, if acceptable under applicable security policies and regulations. (Good policies may prohibit this, but they usually also prohibit getting the privatekey from or providing it to any other system, especially one 'online' somewhere, and your customer is doing the latter.) To retain traditional format do
openssl rsa -in oldfile -out newfile
# and give the passphrase when prompted, or see the man page about -passin
or you can use the 'new' PKCS8 format with
openssl pkey -in oldfile -out newfile
# technically only in release 1.0.0 up, but pretty much everyone is there now
#
# or in all versions back to about 2000
openssl pkcs8 -topk8 -nocrypt -in oldfile -out newfile
For me this error occured after pulling some old code that was workign to a fresh system, I was using too current of a node Version, I downgraded from 17 to 16 and that solved my problem.
Tried checking the github issues related to the TLS, handshake and versions. But couldn't find any.
The final fix was the one suggested by #Greggory Wiley.
Installed nvm - downgraded the node and npm versions. Recomplied the code. And it worked.
In my case I was exporting a certificate from windows to linux inside a docker using openSSL and facing this error.
The problem was in the versions of OpenSLL, when I was converting .pfx file to .crt and .key I was using 3.0.x version on windows, and on linux I had 1.1.1 installed. After I did the same using the same version of OpenSLL on windows it worked.
I had the same issue, I would say that the accepted answer is good expect it does not provide an example where the passphrase is used.
Here's code that worked in my case for express.js
const server = https
.createServer(
{
key: fs.readFileSync("./root/ca/cakey.pem"),
cert: fs.readFileSync("./root/ca/cacert.pem"),
passphrase: "abcdefg",
},
app
)
.listen(PORT, () => {
console.log(`Secure server listening on port:${PORT}`);
});

Public encryption in crypto on node 0.12

I need to encrypt (and decrypt) a string with a public key previously generated in nodejs (i'm using version 0.12) with crypto module, but i'm unable to do it.
For first i generated the keys in this way:
var diffHell = crypto.createDiffieHellman(60);
diffHell.generateKeys('base64');
var publicKey = diffHell.getPublicKey('base64'); //or whatever 'hex','binary'
var privateKey = diffHell.getPrivateKey('base64'); //or whatever 'hex','binary'
Then i tried to encrypt a string using the generated public key:
crypto.publicEncrypt({key: publicKey}, new Buffer(textToEncrypt));
Running this snippet, node throw this error:
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
at Error (native)
at Object.exports.publicEncrypt (crypto.js:362:18)
[...]
Reading it, I understand that the key must be in PEM format, but i can't find in the documentation how to tranform a public key in PEM.
So, How i can do that? Someone has done this yet?
Diffie-Hellman (Key Exchange) is an algorithm and protocol to derive a shared secret based on modular arithmetic. It is not a public-key cipher in the same way as RSA is. You cannot use Diffie-Hellman for crypto.publicEncrypt().
Node.js' Crypto module doesn't provide a way to generate a public-private RSA key pair, so you either need to use OpenSSL through child_process or use one of the many modules which provide this sort of thing (e.g. ursa).
You do not need to uses ursa for key generation. Instead you can generate keys with openssl then store the generated PEM keys on your server and try to load them in your script

How to decrypt an encrypted RSA key .pem file with Node.js

I have an encrypted private key file (I also have the unencrypted one for comparison), assume that I have the password and I want the decrypted version of that file - I tried using the URSA module (npm install ursa) , but it is not suitable for my needs because it is not portable enough (requires a specific version of the .NET framework on Windows). I need a raw Node.js solution - Is there a module that would let me do this?
If not, what is the exact process for turning this encrypted key into a plain key?
I tried using Node.js' crypto module crypto.createDecipher(algorithm, password)... Using 'DES-EDE3-CBC' as the algorithm and my password, but I get giberrish output which doesn't match the unencrypted version of the key. I was running the decryption on the content starting with o5IM... and ending with ==... I also tried only the string from o5IM to OZDug and that didn't work either.
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,0DC77650897F6756
o5IMl6kanVn72mKmvlKHZhz+5YXZsnPvOVLOm9FATNLt/EC+YQgznIlxR3tHYbk/
6YXXS9YeyebJ0uvD0RG14q+zDrWSoE70VsiEDJVj6HUCBe3O7wjaZ6tPLIKXWXtU
Go315e0OCMszafWnWSO5EN8ZSpJSjHCa9b0nJTWu1gyA9Z21c5Gu/jwHi/3Fvk2x
YDAl17RaTSMk2enez8+oqSBre3PTuX+1DWnfZbEWCnWidioPkisfVj5+qkCQmpzV
9OyCZ09S+ygwtEJkG+GdJuIK0oAVK1J6Jlpns7n/b3vbxuV3FxIWJteicujffnom
c9bV63c/9enRJKLV/gU/6JzD1SnpwH8grU5Y7TqHg//eA9XtO1+7Rye/MRgCsEsX
lKLctmB2a7PQWV2Wm9sQhfjI+J0mikuBDIoUp16JIn3UKWGY7g9CRkqwM9ozgVBG
8IoPoKSE/Rys9AkIp0gvQ9HeVUAkMwzWV60D0uKImZEFxkZ1WCcBS8xLc+kWQfwm
Ngh0rpf3AtKIZcatWkTzmpFEcXwRSJDBH8PwJM9UpsOJHmb05UjN54MhyC/HaYV7
n0HToHlOipmOF0Z299/4rxQanVZjC2pfbVi2HbbhWEGlbUI728rhoDvfK1N2eHfy
edGz9Ls6hAMcYrTa4knIMQr5W7iXaTOYDPxSxgsddJfm6AkMo3f0Oaz3+IIpyr+S
UVTCAN3nubHVVWld4xNsqn55zeLLwt4R0MyqgFXeK5CDFN/R7YLnuCm//kV5ozHn
dd43mBt7FtEuAX0pjocXvlQOTjM8quBOtszEj+XkcpgvnjGCkOZDug==
-----END RSA PRIVATE KEY-----

Hex encode ECDSA keys in node.js

I'm building a nodejs app that talks to an API server. The API server requires that each request I make to it includes a X-Signature header using the prime256v1 ECDSA curve and sha256 hash on a particular set of data.
I looked through the crypto and tls documentation but didn't find anything suitable. I have successfully generated a private key with openssl ecparam -name prime256v1 -genkey but it is in PEM format. I have also generated a DER format key. Both of these include some extra metadata like the curve used and in the case of PEM, comments.
I can use these keys for signing operations on my side, but the server requires that I upload a public key using hex encoding (so the server can verify the signatures I make on my requests.)
Specifically the server wants something like the output of the following Python code:
from ecdsa import SigningKey
from binascii import hexlify
hexlify(SigningKey.from_pem(content).to_string())
Sample output for a pubkey (no newlines): c5bd76cd0cd948de17a31261567d219576e992d9066fe1a6bca97496dec634e2c8e06f8949773b300b9f73fabbbc7710d5d6691e96bcf3c9145e15daf6fe07b9
I would prefer not adding python as a dependency to my node app... anyone know of a way I can extract the binary data representing my private key from the PEM or DER files, so I can put it in a buffer and call buffer.toString('hex')? Or a way I can use the native crypto library to generate the ECDSA keypair? Or a library that would do the same?
openssl itself can print out the guts of things, in hex.
Doe the key change? sounds like you can just decode into hex one time, and use that? No need for dependencies - just paste the hex into your node source?

Conversion from cert file to pfx file

Is it possible to convert a cert file to a pfx file? I tried importing my cerf file into IE, but it is never shown under the "personal" tab, thus I cannot export there.
I am looking for if there is alternatives available.
FYI, the cerf file is created by using "keytool" and then doing an export to a cert file.
This article describes two ways of creating a .pfx file from a .cer file:
Maxime Lamure: Create your own .pfx file for ClickOnce
Create your public & private Keys (You will be prompt to define the private key’s password):
makecert.exe -sv MyKey.pvk -n "CN=.NET Ready!!!" MyKey.cer
Create your PFX file from the public and private key
pvk2pfx.exe -pvk MyKey.pvk -spc MyKey.cer -pfx MyPFX.pfx -po toto
Programmaticaly you could do so in C# by writing the byte array directly to a file:
byte[] certificateData = certificate.Export(X509ContentType.Pfx, "YourPassword");
File.WriteAllBytes(#"C:\YourCert.pfx", certificateData);
And generally (if you're using IE 8) you might want to have a look at this answer on SO:
How to make IE8 trust a self-signed certificate in 20 irritating steps
Hope that helps you.

Resources