Ssh pem key linux

Convert pem key to ssh-rsa format

The way you posted in the «This was obtained with this command» worked for me better than any of the answers below.

@YoavShipra. Yes but the whole question is that he wants to convert using only the public key. Maybe he doesn’t have the private key and he only has the public key and wants to convert from PEM format to ssh-rsa format.

Given a .pem from AWS, the command you give above ssh-keygen -y -f private_key1.pem > public_key1.pub worked great for me.

Beauty is in the eye of the beholder. We need to note that a pem key could container either public key or private key, or both; encrypted or maybe not; plus with various format. Also the meaning of option -m is different for -i / -e . So my friends, please make sure you know what you want and what you have. 🙂

11 Answers 11

No need to compile stuff. You can do the same with ssh-keygen :

will read the public key in openssl format from pub1key.pub and output it in OpenSSH format.

Note: In some cases you will need to specify the input format:

ssh-keygen -f pub1key.pub -i -m PKCS8 

From the ssh-keygen docs (From man ssh-keygen):

-m key_format Specify a key format for the -i (import) or -e (export) conversion options. The supported key formats are: “RFC4716” (RFC 4716/SSH2 public or private key), “PKCS8” (PEM PKCS8 public key) or “PEM” (PEM public key). The default conversion format is “RFC4716”.

I added back the more specific, longer format to the answer because it was required by myself and some others. Seems like which works depends on what version of ssh-keygen you are using and/ or input format.

No need for scripts or other ‘tricks’: openssl and ssh-keygen are enough. I’m assuming no password for the keys (which is bad).

Generate an RSA pair

All the following methods give an RSA key pair in the same format

openssl genrsa -out dummy-genrsa.pem 2048 
openssl genpkey -algorithm RSA -out dummy-genpkey.pem -pkeyopt rsa_keygen_bits:2048 
ssh-keygen -t rsa -b 2048 -f dummy-ssh-keygen.pem -N '' -C "Test Key" 

Converting DER to PEM

If you have an RSA key pair in DER format, you may want to convert it to PEM to allow the format conversion below:

openssl genpkey -algorithm RSA -out genpkey-dummy.cer -outform DER -pkeyopt rsa_keygen_bits:2048 
openssl rsa -inform DER -outform PEM -in genpkey-dummy.cer -out dummy-der2pem.pem 

Extract the public key from the PEM formatted RSA pair

openssl rsa -in dummy-xxx.pem -pubout 
ssh-keygen -y -f dummy-xxx.pem 

Notes

[user@test1 ~]# cat /etc/redhat-release ; uname -a ; openssl version CentOS release 6.5 (Final) Linux test1.example.local 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux OpenSSL 1.0.1e-fips 11 Feb 2013 

@NathanBasanese, yes (see «Extract the public key from the PEM formatted RSA pair», point 2): once one has the certificate in pem format: ssh-keygen -y -f dummy-xxx.pem produces an ssh-rsa AAAA[. ]== fit for ssh’s authorized_keys file.

Читайте также:  Virtualbox linux общие папки права

Good informative piece. but I don’t think it really answers the question as well as the above much shorter piece.

By converting it shows: unable to load Private Key 10828:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:.\crypto\a sn1\tasn_dec.c:1200:

To answer my own question, after posting on openssl mailing list got this:

Here is C code to convert from an OpenSSL public key to an OpenSSH public key. You can grab the code from this link and compile it yourself:

static unsigned char pSshHeader[11] = < 0x00, 0x00, 0x00, 0x07, 0x73, 0x73, 0x68, 0x2D, 0x72, 0x73, 0x61>; static int SshEncodeBuffer(unsigned char *pEncoding, int bufferLen, unsigned char* pBuffer) < int adjustedLen = bufferLen, index; if (*pBuffer & 0x80) < adjustedLen++; pEncoding[4] = 0; index = 5; >else < index = 4; >pEncoding[0] = (unsigned char) (adjustedLen >> 24); pEncoding[1] = (unsigned char) (adjustedLen >> 16); pEncoding[2] = (unsigned char) (adjustedLen >> 8); pEncoding[3] = (unsigned char) (adjustedLen ); memcpy(&pEncoding[index], pBuffer, bufferLen); return index + bufferLen; > int main(int argc, char** argv) < int iRet = 0; int nLen = 0, eLen = 0; int encodingLength = 0; int index = 0; unsigned char *nBytes = NULL, *eBytes = NULL; unsigned char* pEncoding = NULL; FILE* pFile = NULL; EVP_PKEY *pPubKey = NULL; RSA* pRsa = NULL; BIO *bio, *b64; ERR_load_crypto_strings(); OpenSSL_add_all_algorithms(); if (argc != 3) < printf("usage: %s public_key_file_name ssh_key_description\n", argv[0]); iRet = 1; goto error; >pFile = fopen(argv[1], "rt"); if (!pFile) < printf("Failed to open the given file\n"); iRet = 2; goto error; >pPubKey = PEM_read_PUBKEY(pFile, NULL, NULL, NULL); if (!pPubKey) < printf("Unable to decode public key from the given file: %s\n", ERR_error_string(ERR_get_error(), NULL)); iRet = 3; goto error; >if (EVP_PKEY_type(pPubKey->type) != EVP_PKEY_RSA) < printf("Only RSA public keys are currently supported\n"); iRet = 4; goto error; >pRsa = EVP_PKEY_get1_RSA(pPubKey); if (!pRsa) < printf("Failed to get RSA public key : %s\n", ERR_error_string(ERR_get_error(), NULL)); iRet = 5; goto error; >// reading the modulus nLen = BN_num_bytes(pRsa->n); nBytes = (unsigned char*) malloc(nLen); BN_bn2bin(pRsa->n, nBytes); // reading the public exponent eLen = BN_num_bytes(pRsa->e); eBytes = (unsigned char*) malloc(eLen); BN_bn2bin(pRsa->e, eBytes); encodingLength = 11 + 4 + eLen + 4 + nLen; // correct depending on the MSB of e and N if (eBytes[0] & 0x80) encodingLength++; if (nBytes[0] & 0x80) encodingLength++; pEncoding = (unsigned char*) malloc(encodingLength); memcpy(pEncoding, pSshHeader, 11); index = SshEncodeBuffer(&pEncoding[11], eLen, eBytes); index = SshEncodeBuffer(&pEncoding[11 + index], nLen, nBytes); b64 = BIO_new(BIO_f_base64()); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bio = BIO_new_fp(stdout, BIO_NOCLOSE); BIO_printf(bio, "ssh-rsa "); bio = BIO_push(b64, bio); BIO_write(bio, pEncoding, encodingLength); BIO_flush(bio); bio = BIO_pop(b64); BIO_printf(bio, " %s\n", argv[2]); BIO_flush(bio); BIO_free_all(bio); BIO_free(b64); error: if (pFile) fclose(pFile); if (pRsa) RSA_free(pRsa); if (pPubKey) EVP_PKEY_free(pPubKey); if (nBytes) free(nBytes); if (eBytes) free(eBytes); if (pEncoding) free(pEncoding); EVP_cleanup(); ERR_free_strings(); return iRet; > 

Источник

Читайте также:  Linux отчет об ошибках

Как сгенерировать .pem ключ на Linux для удаленного подключения?

Я знаю только один способ удаленного подключения, сгенерить пару публичного+приватного ключа на хосте и отправить публичный ключ командой ssh-copy-id на удаленный сервер, при этом первый раз запросит пароль.

Но, например, при создании инстанса в AWS, сразу выдается .pem ключ, что очень удобно при дальнейшем подключении как через MobaXterm, так и через терминал командой ssh -i «key.pem» ubuntu@hostname

Какие действия необходимо совершить для генерирования .pem ключа и последующего его использования? Создать на удаленной машине публичный+приватный ключ и как-то сконвертировать приватный в .pem?

pem это не совсем формат, контейнер, внутри которого может быть сертификат, или цепочка из сертификата, приватного ключа и рутового сертификата.
Следовательно посмотри что у тебя в pem генерируется.

А так — ssh-keygen умеет генерить в PEM формате:
ssh-keygen -t rsa -m PEM

Или конвертнуть существующий:
ssh-keygen -f id_rsa -e -m pem

А так, современая версия ssh-keygen и так генерит ключ в валидном pem формате.

Saboteur спасибо за пояснение, что pem это не совсем формат и современная версия ssh-keygen и так генерит ключ в валидном pem формате.

Я ещё раз полез читать про ключи и, как оказалось, проблема была в том, что я передал на хост private key удаленного сервера и пытался по этому ключу подключиться, но при этом public key удаленного сервера, не был записан в файле authorized_keys удаленного сервера. Поэтому сервер скипал private key, так как public key не было в файле authorized_keys.

Вопрос, если я хочу добавить public key хоста на удаленный сервер, я использую команду ssh-copy-id user@hostname, но если на удаленном сервере отключена аутентификация по паролю, то такой вариант не сработает. Вопрос, как добавить public key на удаленный сервер не зная пароля? Только прописать public key в authorized_keys вручную, где снова таки надо знать пароль для подключения?

Именно так.
Либо админ удаленного сервера должен прописать ваш ключ, либо вы получаете временный пароль на удаленном сервере чтобы могли это сделать.
Ну а иначе никак. В противном случае ЛЮБОЙ бы мог прописать свой ssh ключ на вашем сервере )

Источник

ssh by pem file to Access Server

It is a standard procedure, now how to make this work without using password, using just a .pem file?

PEM or Privacy Enhanced Mail is a Base64 encoded DER certificate. PEM certificates are frequently used for web servers as they can easily be translated into readable data using a simple text editor. Generally when a PEM encoded file is opened in a text editor, it contains very distinct headers and footers.

PEM is a widely used encoding format for security certificates. Syntax and content is defined by X.509 v3 standards for digital certificates, defined in IETF RFC 5280 specifications. The main file extensions are .pem, .crt, .ca-bundle.

A PEM certificate is a base64 (ASCII) encoded block of data encapsulated between

-----BEGIN CERTIFICATE REQUEST----- ……. And …… -----END CERTIFICATE REQUEST-----

Above is the example of a CSR (certificate signing request) in PEM format. You can see that PEM has the characteristics of containing a header, the body (which consists mainly of code) and footer.

Читайте также:  Linux server backup software

The header and footer is what identifies the type of file, however be aware that not all PEM files necessarily need them.

-----BEGIN CERTIFICATE REQUEST----- and -----END CERTIFICATE REQUEST----- show a CSR in PEM format. -----BEGIN RSA PRIVATE KEY----- and -----END RSA PRIVATE KEY----- show a private key in PEM format. -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- show a certificate file in PEM format.

To ssh using pem file there are few steps you have to follow

1.Generating Key Pairs

To generate an RSA key pair for version 2 of the SSH protocol, follow these steps:

$ ssh-keygen or $ ssh-keygen -t rsa -b 2048 -v

Optional: To increase the security of your key, increase the size with the –b flag. The minimum value is 768 bytes and the default, if you do not use the flag, is 2048 bytes. We recommend a 4096 byte key:

  • And when asked to enter file in which to save the key, type linux_point and when asked to enter passphrase, press Enter (empty passphrase) and confirm by
$ ls  linux_point linux_point.pub 
  • Here we will get two files generated, one will be my-certificate and one will be pub, rename the my-certificate to linux_point.pem, so you will have two files, linux_point.pub and linux_point.pem
 $ mv linux_point linux_point.pem
$ chmod 700 ~/.ssh
  • Create a file ~/.ssh/authorized_keysif already exist ignore this step
$ vim  ~/.ssh/authorized_keys
  • Changes are made in file ~/.ssh/authorized_keys such as copy the pub in file ~/.ssh/authorized_keys on the machine to which you want to connect, appending it to its end if the file already exists.
  • And Change the permissions of the ~/.ssh/authorized_keys file using the following command:
$ chmod 600 ~/.ssh/authorized_keys 

Now download the pem file (linux_point.pem) in your drive or system from where you want to Access the Server.

Using Key-Based Authentication

To improve the system security even further, you can enforce key-based authentication by disabling the standard password authentication. To do so, open the /etc/ssh/sshd_config configuration file in a text editor such as vim, and change or uncomment if exist the option as follows:

$ sudo vim /etc/ssh/sshd_config RSAAuthentication yes PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys PasswordAuthentication no # Change to no to disable s/key passwords ChallengeResponseAuthentication no #UsePAM no UsePAM yes Save and exit (:wq) 

After that restart sshd service

$ sudo systemctl restart sshd or $ sudo service sshd restart 

Now access the server by ssh through pem file ( without password ) from local.

$ ssh –i linux_point.pem)> user>linux_point@ Last login: Mon Jul 17 15:35:38 2017 from XXX.XXX.XXX.XX  [linuxpoint@XXX.XXX.XXX.XX ~]$ _

Like and share @Thank you

Источник

Оцените статью
Adblock
detector