Ssl error no start line

Nginx SSL Certificate Errors: PEM_read_bio_X509_AUX, PEM_read_bio_X509, SSL_CTX_use_PrivateKey_file Mattias Geniar, August 13, 2015 Follow me on Twitter as @mattiasgeniar When configuring your SSL certificates on Nginx, it’s not uncommon to see several errors when you try to reload your Nginx configuration, to activate the SSL Certificates. This post describes the following type of errors: Read […]

Содержание

  1. Nginx SSL Certificate Errors: PEM_read_bio_X509_AUX, PEM_read_bio_X509, SSL_CTX_use_PrivateKey_file
  2. Nginx PEM_read_bio_X509: ASN1_CHECK_TLEN:wrong tag error
  3. Nginx PEM_read_bio_X509_AUX: Expecting: TRUSTED CERTIFICATE
  4. Nginx SSL_CTX_use_PrivateKey_file: bad base64 decode error
  5. Please tutorial how to fix «error:0909006C:PEM routines:get_name:no start line» with algorithm: «RS256» #642
  6. Comments
  7. Description
  8. Reproduction
  9. Environment
  10. This comment has been minimized.
  11. nginx SSL без начальной строки: ожидание: ДОВЕРЕННЫЙ СЕРТИФИКАТ

Nginx SSL Certificate Errors: PEM_read_bio_X509_AUX, PEM_read_bio_X509, SSL_CTX_use_PrivateKey_file

Mattias Geniar, August 13, 2015

Follow me on Twitter as @mattiasgeniar

When configuring your SSL certificates on Nginx, it’s not uncommon to see several errors when you try to reload your Nginx configuration, to activate the SSL Certificates.

This post describes the following type of errors:

Read on for more details.

Nginx PEM_read_bio_X509: ASN1_CHECK_TLEN:wrong tag error

These kind of errors pop up when your certificate file isn’t valid. The entire error looks like this.

You should fix this by beginning to read the SSL certificate info via the CLI. Chances are, OpenSSL will also show you an error, to confirm your SSL certificate isn’t valid.

In the example above, the SSL certificate is in /etc/nginx/ssl/mydomain.tld/certificate.crt , so the following examples continue to use that file.

If that’s your output, you have confirmation: your SSL certificate is corrupt. It’s got unsupported ASCII characters, it’s missing a part, some copy/paste error caused extra data to be present, … Bottom line: your certificate file won’t work.

You can test a few things yourself, like new line issues (linux vs. windows remains a problem). Open the file in binary mode in vi , and if you see ^M at end of every line, you’ve incorrectly got Windows new lines instead of Unix new lines.

Remove all new lines and replace them with “normal” unix new lines ( n instead of rn ).

If your SSL certificate file contains multiple certificates, like intermediate or CA root certificates, it’s important to check each of them separately. You can check this by counting the «-—-BEGIN CERTIFICATE-—-« lines in the file.

If you’ve got multiple certificates, copy/paste each one to a different file and run the openssl example above. Each should give you valid output from the SSL certificate.

The output above shows that the SSL Certificate file contains 3 individual SSL certificates. Copy/paste them all in separate files and validate if they work. If one of them gives you errors, fix that one: find the wrong ASCII characters, fix the new lines, check if you copy/pasted it correctly from your vendor, …

The “nginx: [emerg] PEM_read_bio_X509” error means your Nginx configuration is probably correct, it’s the SSL certificate file itself that is invalid.

Nginx PEM_read_bio_X509_AUX: Expecting: TRUSTED CERTIFICATE

This is an error that is usually resolved very quickly. The certificate file you’re pointing your config to, isn’t a certificate file. At least, not according to Nginx.

This can happen if you’ve accidentally swapped your private key and SSL certificate in either your files, or in the Nginx configuration.

Your Nginx config will contain these kind of lines for its SSL configuration.

Check if the ssl_certificate file is indeed your SSL certificate and if the ssl_certificate_key is indeed your key. It’s not uncommon to mix these up if you’re in a hurry or distracted and save the wrong contents to the wrong file.

Nginx SSL_CTX_use_PrivateKey_file: bad base64 decode error

Another common error in Nginx configurations is the following one.

Note how the Nginx SSL error points to the .key file this time. The problem is with the SSL key, not the SSL certificate.

This error indicates that the private key you pointed your configuration to, doesn’t match the SSL Certificate.

You can validate whether private key and SSL certificate match by calculating their MD5 hash. If they don’t match, you have to find either the right certificate or the right private key file.

One of them is wrong and needs to be replaced. With this error, it’s impossible to know which one is wrong. Your best bet is to read the info from the SSL certificate, determine if that’s the correct SSL certificate (check expiration date, SANs, Common Name, …), and find the matching key (which should have been created when you generated your Certificate Signing Request, CSR).

Источник

Please tutorial how to fix «error:0909006C:PEM routines:get_name:no start line» with algorithm: «RS256» #642

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Please read through the template below and answer all relevant questions. Your additional work here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Description

Provide a clear and concise description of the issue, including what you expected to happen.

Reproduction

Detail the steps taken to reproduce this error, what was expected, and whether this issue can be reproduced consistently or if it is intermittent.

Where applicable, please include:

  • Code sample to reproduce the issue
  • Log files (redact/remove sensitive information)
  • Application settings (redact/remove sensitive information)
  • Screenshots

Environment

  • Version of this library used:
  • Version of the platform or framework used, if applicable:
  • Other relevant versions (language, server software, OS, browser):
  • Other modules/plugins/libraries that might be involved:

The text was updated successfully, but these errors were encountered:

I have the same issue.
please give me solution if you have

I’ve hidden your suggestion. The point behind using an RS private key is so that noone but you can produce the signatures but everyone with the knowledge of your public key can verify it. HS256 is an HMAC based symmetric key (secret) algorithm and you’d be using the octets of malformed private key as the shared symmetric secret. DON’T DO THAT.

error:0909006C:PEM routines:get_name:no start line

How to fix it? Provide a properly formatted pkcs8 , pkcs1 , or sec1 PEM private key. That’s really it.

Create JWT Token using the command shown here. This most probably will fix the issue.

Also don’t miss the openssl command, it’s important, else you might get an error — #68 (comment)

For us we had this issue while loading a private key from ENV instead of files (because of automated deployment in aws).

We fixed it by replacing n in the env var with real line breaks
process.env.JWT_PRIVATE_KEY.replace(/\n/gm, ‘n’)

Hope this helps someone

Continuing with @derN3rd ‘s answer, I had to approach this slightly differently.

For me, I was storing my private rsa key in a Gitlab CI/CD environment variable, which I was then reading into a file (this file was then read by the code I was testing).

Where I was going wrong was in the echo statement. As you see above, I am surrounding the environment variable with double-quotes. This is significant because by surrounding the variable with double-quotes, it preserves the n character in the private key.

When I was just using the statement echo $MY_PRIV_KEY_ENV_VARIABLE > priv_key.pem , it was adding spaces where the n character was and causing the error mentioned in this issue error:0909006C:PEM

For us we had this issue while loading a private key from ENV instead of files (because of automated deployment in aws).

We fixed it by replacing n in the env var with real line breaks
process.env.JWT_PRIVATE_KEY.replace(/\n/gm, ‘n’)

Hope this helps someone

Very useful, tks.

Just to add a bit of clarification to @derN3rd ‘s solution, which is great btw, adding n s to the env variable is a necessary step, prior to replacing them on the client side.

I also did not use quotes to surround the value.

Something like this:

i mean if we validate the file’s contents with openssl then there must be some other problem going on?

For Windows users with PowerShell and OpenSSL.Light installed who needs to extract everything between —-BEGIN CERTIFICATE—— and —-END CERTIFICATE—— :

I got this because I was accidentally signing with my public key 🤦‍♀️

For us we had this issue while loading a private key from ENV instead of files (because of automated deployment in aws).

We fixed it by replacing n in the env var with real line breaks
process.env.JWT_PRIVATE_KEY.replace(/\n/gm, ‘n’)

Hope this helps someone

I selected every reaction. This helped me so so so much. THANK YOU @derN3rd

Just to add a bit of clarification to @derN3rd ‘s solution, which is great btw, adding n s to the env variable is a necessary step, prior to replacing them on the client side.

I also did not use quotes to surround the value.

Something like this:

Right, thank you, that clarification helped.

In our case I saved it this way in a Bitbucket repo variable and then was able to create the file in a Bitbucket pipeline since echo -e will interpret the n, i.e.
— echo -e $JWT_KEY > build/keys/server.key

For us we had this issue while loading a private key from ENV instead of files (because of automated deployment in aws).

We fixed it by replacing n in the env var with real line breaks
process.env.JWT_PRIVATE_KEY.replace(/\n/gm, ‘n’)

Hope this helps someone

For me it did not work in Google Cloud Platform Cloud Functions. Deploy works but function crashes with the error code.
I got tired of the error so I use a javascript string litteral and copy pasted my private key there instead of the process.env variable

iconv -c -f UTF8 -t ASCII myprivate.key >> myprivate.key

Converting from utf-8 to ASCII made it work for me 😄

I was placing the key and crt interchangeably. So placing it rightly solve mine.

I accidentally exchanged private key and certificate.

This is the complete solution of the problem.
First to generate SSL certificates, then create a HTTPS server via these certificates, after that implement Secure Web Sockets.
1st:
Generate SSL certificates via OPENSSL.
These are the 3 commands

openssl genrsa -out abels-key.pem 2048
openssl req -new -sha256 -key abels-key.pem -out abels-csr.pem
openssl x509 -req -in abels-csr.pem -signkey abels-key.pem -out abels-cert.pem

2nd: Code
const express = require(«express»);
const https = require(«https»);
const fs = require(«fs»);
const WebSocket = require(«ws»);

const app = express();
let cert = fs.readFileSync(«abels-cert.pem»);
let key = fs.readFileSync(«abels-key.pem»);
const options = <
key,
cert,
>;

app.get(«/», async (req, res) => <
res.send(«Server is Running on HTTPs and WSS»);
>);

var server = https.createServer(options, app);

server.listen(443, () => <
console.log(«Server is Running on PORT 443»);
>);

const wss = new WebSocket.Server(< server >);

wss.on(«connection», function connection(ws) <
console.log(«Connection has been established successfully»);
ws.on(«message», function incoming(message) <
console.log(«received: %s», message);
>);

Note:
In Online server you may face 3 problems,
1st PORT
2nd (URL), WSS will not work with IP Address (In my Case new WebSocket(«wss://localhost») its work fine, new WebSocket(«wss://127.0.0.1 or wss://127.0.0.1:443»)) not working as expected.
3rd Certificates issues.

There are some online resources which helps us to validate our certificates

Источник

nginx SSL без начальной строки: ожидание: ДОВЕРЕННЫЙ СЕРТИФИКАТ

У меня закончились идеи, и мне нужна помощь, пожалуйста!

Я создаю свой SSL с помощью Openssl следующим образом:

Cert.pem выглядит так:

Key.pem выглядит так:

В docker-compose у меня есть сертификат / ключ, отправленный в etc / nginx / ssl / .

В nginx я добавил это так:

Когда я запускаю docker-compose, я получаю эту ошибку с nginx:

Я работаю над этим уже несколько дней, и я не уверен, почему я продолжаю получать эту ошибку. Я пробовал сделать это crt / key вместо .pem и получаю ту же ошибку. Если я просто удалю ssl все вместе, сервер будет работать нормально, но мне очень нужен SSL. Pleeeaaase помогите!

«Обычный» сертификат, закодированный в PEM, будет выглядеть так:

( . это кодировка DER структуры Base64 )

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

В качестве примечания: поскольку это кажется популярным (неправильным) мнением, само по себе имя файла, включая расширение, явно не влияет на рабочий (или нет) статус контента. Вы можете давать своим файлам имена, foobar.42 и, buzz.666 если их содержимое является допустимым, они также будут работать . конечно, обслуживание человеком будет сложнее, отсюда и соглашение о частом .crt использовании сертификата (или .cert для ограниченных сред, не основанных на DOS) и .key для ключевого файла и обычно используется имя сайта (для веб-сайта) или его часть в качестве имени, например example.com.crt . Но опять же, это только один из возможных наборов соглашений, и любая программа, нуждающаяся в этих файлах, не заботится об имени, а только о содержимом. Некоторые также используют .pem расширение.

См. Https://en.wikipedia.org/wiki/X.509#Certificate_filename_extensions для всего вышеперечисленного, в нем есть хорошее обсуждение / представление вариантов.

Теперь в вашем случае сообщение об ошибке сообщало вам, что ожидается, что контент будет написан как таковой:

единственное отличие — добавленное TRUSTED ключевое слово. Но почему и когда это происходит?

Сертификат подписывается одним «центром сертификации» через одного или нескольких промежуточных звеньев. Это создает цепочку доверия до корневого сертификата, где издатель равен субъекту, этот сертификат подписывает себя.

Вы сами сгенерировали свой сертификат, поэтому это «самоподписанный» сертификат, технически неотличимый от сертификата CA, за исключением того, что никакая система по умолчанию, включая вашу собственную, не будет доверять такому сертификату без определенной конфигурации.

Это в основном то, что сообщает вам сообщение об ошибке: приложение сообщает, что загружает сертификат на основе вашей конфигурации, который он не может проверить (потому что он самоподписанный), и в то же время вы явно не настроили его для доверия.

Источник

«no start line error» при подключении SSL сертификата

Добрый вечер, проблемы с подключением SSL сертификата, в конфиг nginx ввожу следующее:

Собственно содержимое файлов следующее:

Код соответственно после фразы START CERTIFICATE разный (Я написал так для примере), в каждой строчке по 64 символа, ну кроме последней. Так вот ошибка в следующем, при перезапуске nginx получаю ошибку:

Так ошибка указывает не на ключ, ключ сделан аналогично сертификату, так же начинается с BEGIN и заканчивается END

Ключ и сертификат взяты с CloudFlare, созданы мною

Исходя из этого я получил от них код CERTIFICATE и код PRIVATE KEY, собственно создал два файла: 1) rak.pem (Туда вставил код CERTIFICATE) 2) rak.key (Туда вставил код PRIVATE KEY)

Далее уже описано выше

1 ответ 1

Директивы у вас верные и делаете по инструкции, а вот с ключом (точнее — с файлом закрытого ключа) что-то не так.

Только ради бога, не выкладывайте в вопрос свой приватный ключ, ладно? 🙂 (Зная пару закрытый ключ — публичный ключ можно подписать любое сообщение от вашего имени)

Приватный ключ, который вы указываете в ssl_certificate_key должен начинаться с:

——BEGIN PRIVATE KEY——

Судя по описанию ошибки — при такой простой на первый взгляд операции как «вставить текст в файл и сохранить» — важно, как у вас оформлены переводы строк. Типовые ошибки можно почитать тут (на английском): https://stackoverflow.com/questions/20837161/openssl-pem-routinespem-read-biono-start-linepem-lib-c703expecting-truste

Поэтому берём какой-нибудь текстовый редактор, который показывает переводы строк (Notepad++, Sublime и т.п.) и внимательно проверяем свои файлы. Например, что файл находится в кодировке UTF-8 без BOM.

Источник

nginx SSL no start line: expecting: TRUSTED CERTIFICATE

I’m out of ideas and I need help please!

I create my SSL using Openssl with this:

The cert.pem looks like this:

The key.pem looks like this:

In docker-compose I have the cert/key sent to etc/nginx/ssl/.

In nginx I have it added like this:

When I start up docker-compose, I get this error with nginx:

I’ve been working on this for several days now and I’m not sure why I keep getting this error. I’ve tried making it crt/key instead of .pem and I get the same error. If I just remove ssl all together the server works fine, but I need SSL very badly. Pleeeaaase help!

3 Answers 3

A «normal» certificate, once encoded in PEM will look like this:

(the . is Base64 encoding of a DER structure)

This is normally (with the associated key, typically in separate file) the thing needed by any TLS enabled application when it wants to show its identity to the remote end.

As a side note, since it seems to be popular (wrong) belief, the filename by itself, including the extension, has explicitly no consequences on the working (or not) status of the content. You can name your files foobar.42 and buzz.666 and if their content is valid they will work as well. of course maintenance by the human would be harder, hence the convention of using often .crt for a certificate (or .cert for non-DOS based constrained environments) and .key for a keyfile, and using typically the site name (for a website) or part of it for the name, such as example.com.crt . But again, those are only one possible set of conventions, and any program needing these files do not care about the name, just the content. Some are using the .pem extension also.

See https://en.wikipedia.org/wiki/X.509#Certificate_filename_extensions for all the above it has a good discussion/presentation of options.

Now in your case the error message was telling you it expected to have a content written as such:

the only difference being the added TRUSTED keyword. But why, and when does it happen?

A certificate is signed by one «certificate authority» through one or more intermediates. This builds a chain of trust up to a root certificate, where the issuer is equal to the subject, this certificate signs itself.

You generated your certificate yourself, so this is a «self-signed» certificate, indistinguishable technically from a CA certificate, except that no system by default, including your own, will give trust to such certificate without specific configuration.

This is basically what the error message tells you: the application says it is loading a certificate based on your configuration that it can not validate (because it is self signed) and at the same time you did not explicitely configure it to trust it.

Источник

Can’t get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

I have a .key file, when I do

openssl rsa -text -in file.key

Also I have a .cer file and when I do

openssl x509 -text -in file.cer

But if as pointed here I run the command like:

openssl x509 -text -inform DER -in file.cer

But that doesn’t seem to work with the key, because when I run

openssl rsa -text -inform DER -in aaa010101aaa__csd_10.key

How can I get the private key and its certificate?

5 Answers 5

I ran into the ‘Expecting: ANY PRIVATE KEY’ error when using openssl on Windows (Ubuntu Bash and Git Bash had the same issue).

The cause of the problem was that I’d saved the key and certificate files in Notepad using UTF8. Resaving both files in ANSI format solved the problem.

It looks like you have a certificate in DER format instead of PEM . This is why it works correctly when you provide the -inform PEM command line argument (which tells openssl what input format to expect).

It’s likely that your private key is using the same encoding. It looks as if the openssl rsa command also accepts a -inform argument, so try:

A PEM encoded file is a plain-text encoding that looks something like:

While DER is a binary encoding format.

Update

Sometimes keys are distributed in PKCS#8 format (which can be either PEM or DER encoded). Try this and see what you get:

You need re-encrypt the ssh key file with the -m PEM option.

This issue is caused by the some version of ssh-keygen generated encrypted file format which is not openssl wanted.

I had same issue when I used ssh-keygen -p -f keyfile to encrypt the key file, the result will be like

then I encountered this issue: openssl rsa does not work with same error as the questioner.

The other day I happened find that another encrypted key file was like

and this file could be decrypted by openssl rsa .

It turns out that different ssh-keygen generates different encrypted format, and need respective openssl version to decrypt.

It seems for modern openssl (mine is 1+), it need the latter format.

So I ended up with following solution: re-encrypt the ssh key file with the -m PEM option.

then enter for old password and new password.

The -m PEM option will generate

Then I can use the openssl rsa to decrypt the file later. (Of course if you enter empty password in the above ssh-keygen command, you will also get decrypted result, but that is probably not what you want because you don’t want save a decrypted key file on disk).

Источник

Nginx SSL Certificate Errors: PEM_read_bio_X509_AUX, PEM_read_bio_X509, SSL_CTX_use_PrivateKey_file

Mattias Geniar, August 13, 2015

Follow me on Twitter as @mattiasgeniar

When configuring your SSL certificates on Nginx, it’s not uncommon to see several errors when you try to reload your Nginx configuration, to activate the SSL Certificates.

This post describes the following type of errors:

Read on for more details.

Nginx PEM_read_bio_X509: ASN1_CHECK_TLEN:wrong tag error

These kind of errors pop up when your certificate file isn’t valid. The entire error looks like this.

You should fix this by beginning to read the SSL certificate info via the CLI. Chances are, OpenSSL will also show you an error, to confirm your SSL certificate isn’t valid.

In the example above, the SSL certificate is in /etc/nginx/ssl/mydomain.tld/certificate.crt , so the following examples continue to use that file.

If that’s your output, you have confirmation: your SSL certificate is corrupt. It’s got unsupported ASCII characters, it’s missing a part, some copy/paste error caused extra data to be present, … Bottom line: your certificate file won’t work.

You can test a few things yourself, like new line issues (linux vs. windows remains a problem). Open the file in binary mode in vi , and if you see ^M at end of every line, you’ve incorrectly got Windows new lines instead of Unix new lines.

Remove all new lines and replace them with “normal” unix new lines ( n instead of rn ).

If your SSL certificate file contains multiple certificates, like intermediate or CA root certificates, it’s important to check each of them separately. You can check this by counting the «-—-BEGIN CERTIFICATE-—-« lines in the file.

If you’ve got multiple certificates, copy/paste each one to a different file and run the openssl example above. Each should give you valid output from the SSL certificate.

The output above shows that the SSL Certificate file contains 3 individual SSL certificates. Copy/paste them all in separate files and validate if they work. If one of them gives you errors, fix that one: find the wrong ASCII characters, fix the new lines, check if you copy/pasted it correctly from your vendor, …

The “nginx: [emerg] PEM_read_bio_X509” error means your Nginx configuration is probably correct, it’s the SSL certificate file itself that is invalid.

Nginx PEM_read_bio_X509_AUX: Expecting: TRUSTED CERTIFICATE

This is an error that is usually resolved very quickly. The certificate file you’re pointing your config to, isn’t a certificate file. At least, not according to Nginx.

This can happen if you’ve accidentally swapped your private key and SSL certificate in either your files, or in the Nginx configuration.

Your Nginx config will contain these kind of lines for its SSL configuration.

Check if the ssl_certificate file is indeed your SSL certificate and if the ssl_certificate_key is indeed your key. It’s not uncommon to mix these up if you’re in a hurry or distracted and save the wrong contents to the wrong file.

Nginx SSL_CTX_use_PrivateKey_file: bad base64 decode error

Another common error in Nginx configurations is the following one.

Note how the Nginx SSL error points to the .key file this time. The problem is with the SSL key, not the SSL certificate.

This error indicates that the private key you pointed your configuration to, doesn’t match the SSL Certificate.

You can validate whether private key and SSL certificate match by calculating their MD5 hash. If they don’t match, you have to find either the right certificate or the right private key file.

One of them is wrong and needs to be replaced. With this error, it’s impossible to know which one is wrong. Your best bet is to read the info from the SSL certificate, determine if that’s the correct SSL certificate (check expiration date, SANs, Common Name, …), and find the matching key (which should have been created when you generated your Certificate Signing Request, CSR).

Источник

Please tutorial how to fix «error:0909006C:PEM routines:get_name:no start line» with algorithm: «RS256» #642

Comments

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Please read through the template below and answer all relevant questions. Your additional work here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Description

Provide a clear and concise description of the issue, including what you expected to happen.

Reproduction

Detail the steps taken to reproduce this error, what was expected, and whether this issue can be reproduced consistently or if it is intermittent.

Where applicable, please include:

  • Code sample to reproduce the issue
  • Log files (redact/remove sensitive information)
  • Application settings (redact/remove sensitive information)
  • Screenshots

Environment

  • Version of this library used:
  • Version of the platform or framework used, if applicable:
  • Other relevant versions (language, server software, OS, browser):
  • Other modules/plugins/libraries that might be involved:

The text was updated successfully, but these errors were encountered:

I have the same issue.
please give me solution if you have

This comment has been minimized.

I’ve hidden your suggestion. The point behind using an RS private key is so that noone but you can produce the signatures but everyone with the knowledge of your public key can verify it. HS256 is an HMAC based symmetric key (secret) algorithm and you’d be using the octets of malformed private key as the shared symmetric secret. DON’T DO THAT.

error:0909006C:PEM routines:get_name:no start line

How to fix it? Provide a properly formatted pkcs8 , pkcs1 , or sec1 PEM private key. That’s really it.

Create JWT Token using the command shown here. This most probably will fix the issue.

Also don’t miss the openssl command, it’s important, else you might get an error — #68 (comment)

For us we had this issue while loading a private key from ENV instead of files (because of automated deployment in aws).

We fixed it by replacing n in the env var with real line breaks
process.env.JWT_PRIVATE_KEY.replace(/\n/gm, ‘n’)

Hope this helps someone

Continuing with @derN3rd ‘s answer, I had to approach this slightly differently.

For me, I was storing my private rsa key in a Gitlab CI/CD environment variable, which I was then reading into a file (this file was then read by the code I was testing).

Where I was going wrong was in the echo statement. As you see above, I am surrounding the environment variable with double-quotes. This is significant because by surrounding the variable with double-quotes, it preserves the n character in the private key.

When I was just using the statement echo $MY_PRIV_KEY_ENV_VARIABLE > priv_key.pem , it was adding spaces where the n character was and causing the error mentioned in this issue error:0909006C:PEM

For us we had this issue while loading a private key from ENV instead of files (because of automated deployment in aws).

We fixed it by replacing n in the env var with real line breaks
process.env.JWT_PRIVATE_KEY.replace(/\n/gm, ‘n’)

Hope this helps someone

Very useful, tks.

Just to add a bit of clarification to @derN3rd ‘s solution, which is great btw, adding n s to the env variable is a necessary step, prior to replacing them on the client side.

I also did not use quotes to surround the value.

Something like this:

i mean if we validate the file’s contents with openssl then there must be some other problem going on?

For Windows users with PowerShell and OpenSSL.Light installed who needs to extract everything between —-BEGIN CERTIFICATE—— and —-END CERTIFICATE—— :

I got this because I was accidentally signing with my public key 🤦‍♀️

For us we had this issue while loading a private key from ENV instead of files (because of automated deployment in aws).

We fixed it by replacing n in the env var with real line breaks
process.env.JWT_PRIVATE_KEY.replace(/\n/gm, ‘n’)

Hope this helps someone

I selected every reaction. This helped me so so so much. THANK YOU @derN3rd

Just to add a bit of clarification to @derN3rd ‘s solution, which is great btw, adding n s to the env variable is a necessary step, prior to replacing them on the client side.

I also did not use quotes to surround the value.

Something like this:

Right, thank you, that clarification helped.

In our case I saved it this way in a Bitbucket repo variable and then was able to create the file in a Bitbucket pipeline since echo -e will interpret the n, i.e.
— echo -e $JWT_KEY > build/keys/server.key

For us we had this issue while loading a private key from ENV instead of files (because of automated deployment in aws).

We fixed it by replacing n in the env var with real line breaks
process.env.JWT_PRIVATE_KEY.replace(/\n/gm, ‘n’)

Hope this helps someone

For me it did not work in Google Cloud Platform Cloud Functions. Deploy works but function crashes with the error code.
I got tired of the error so I use a javascript string litteral and copy pasted my private key there instead of the process.env variable

iconv -c -f UTF8 -t ASCII myprivate.key >> myprivate.key

Converting from utf-8 to ASCII made it work for me 😄

I was placing the key and crt interchangeably. So placing it rightly solve mine.

I accidentally exchanged private key and certificate.

This is the complete solution of the problem.
First to generate SSL certificates, then create a HTTPS server via these certificates, after that implement Secure Web Sockets.
1st:
Generate SSL certificates via OPENSSL.
These are the 3 commands

openssl genrsa -out abels-key.pem 2048
openssl req -new -sha256 -key abels-key.pem -out abels-csr.pem
openssl x509 -req -in abels-csr.pem -signkey abels-key.pem -out abels-cert.pem

2nd: Code
const express = require(«express»);
const https = require(«https»);
const fs = require(«fs»);
const WebSocket = require(«ws»);

const app = express();
let cert = fs.readFileSync(«abels-cert.pem»);
let key = fs.readFileSync(«abels-key.pem»);
const options = <
key,
cert,
>;

app.get(«/», async (req, res) => <
res.send(«Server is Running on HTTPs and WSS»);
>);

var server = https.createServer(options, app);

server.listen(443, () => <
console.log(«Server is Running on PORT 443»);
>);

const wss = new WebSocket.Server(< server >);

wss.on(«connection», function connection(ws) <
console.log(«Connection has been established successfully»);
ws.on(«message», function incoming(message) <
console.log(«received: %s», message);
>);

Note:
In Online server you may face 3 problems,
1st PORT
2nd (URL), WSS will not work with IP Address (In my Case new WebSocket(«wss://localhost») its work fine, new WebSocket(«wss://127.0.0.1 or wss://127.0.0.1:443»)) not working as expected.
3rd Certificates issues.

There are some online resources which helps us to validate our certificates

Источник

Recently i was migrating an Apache HTTP Server (httpd) server from one linux machine to another. The problem was, that on the source linux machine Apache HTTP Server (httpd) was a custom compiled 2.4.4 and we were having constant problems when patching the linux machine (openssl libraries etc.). So we decided to replace the custom compiled Apache HTTP Server (httpd) with the RPM version of it but still wanted to stay on 2.4.X version – do not like going back to CentOS/RHEL repository 2.2 Apache HTTP Server versions.

Since all our machines are virtual machines, it is much easier to deploy a new virtual machine from template, install & update the required RPM packages and migrate the apache configuration to the new linux machine – and it is way more cleaner too! 🙂

SSL Library Error: error:0906D06C:PEM - Apache Error

SSL Library Error: error:0906D06C:PEM – Apache Error

I built the latest Apache HTTP Server RPM (version 2.4.9) which i also described in THIS how to and started the process of migration – just for additional info, our Apache HTTP Server instance is only used as a proxy server.

So after installing the Apache HTTP Server 2.4.9 from RPM and transfering the Apache HTTP Server configuration from the source machine i tried to start Apache to check if any errors exist (ofcourse small configuration change was inevitable). The Apache HTTP Server would not start, it said FAILED and the error in /var/log/httpd/ssl_error.log was:

[Fri Aug 08 15:40:30.908717 2014] [ssl:emerg] [pid 8242:tid 139656074909504] AH02562: Failed to configure certificate 192.168.1.3:443:0 (with chain), check /etc/httpd/ssl/geekpeek.cer
[Fri Aug 08 15:40:30.908864 2014] [ssl:emerg] [pid 8242:tid 139656074909504] SSL Library Error: error:0906D06C:PEM routines:PEM_read_bio:no start line (Expecting: TRUSTED CERTIFICATE) -- Bad file contents or format - or even just a forgotten SSLCertificateKeyFile?
[Fri Aug 08 15:40:30.908888 2014] [ssl:emerg] [pid 8242:tid 139656074909504] SSL Library Error: error:140DC009:SSL routines:SSL_CTX_use_certificate_chain_file:PEM lib

Let’s Fix SSL Library Error: error:0906D06C:PEM – Apache Error!

1. Check Certificate With OpenSSL

I started checking certificate key and certificate for errors. After checking certificate /etc/httpd/ssl/geekpeek.cer this is what i got:

[root@geekpeek ~]# openssl x509 -in /etc/httpd/ssl/geekpeek.cer -text -noout
unable to load certificate
140028248876872:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

This “SSL Library Error: error:0906D06C:PEM” error is the same error we get in /var/log/httpd/ssl_error.log.

A bit of googling got me to THIS great webpage which says i quote “If you get the folowing error it means that you are trying to view a DER encoded certifciate and need to use the commands in the “View DER encoded certificate  below””. This is good news for us!

2. View DER Encoded Certificate With OpenSSL

By running the following command i confirmed that the certificate was in DER format since the DID NOT exit with “SSL Library Error: error:0906D06C:PEM” error again but showed certificate information:

[root@geekpeek ~]# openssl x509 -in /etc/httpd/ssl/geekpeek.cer -inform der -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 
......

3. Convert DER Certificate To PEM With OpenSSL

For Apache to be able to read the certificate and therefore successfully start we need to convert DER certificate to PEM by running the following command:

[root@geekpeek ~]# openssl x509 -inform der -in /etc/httpd/ssl/geekpeek.cer -out /etc/httpd/ssl/geekpeek.pem

And voila!

Change the Apache configuration to point to the newly created PEM certificate and Apache should start without “SSL Library Error: error:0906D06C:PEM” error!

When configuring your SSL certificates on Nginx, it’s not uncommon to see several errors when you try to reload your Nginx configuration, to activate the SSL Certificates.

This post describes the following type of errors:

  • PEM_read_bio_X509: ASN1_CHECK_TLEN:wrong tag error
  • PEM_read_bio_X509_AUX: Expecting: TRUSTED CERTIFICATE
  • SSL_CTX_use_PrivateKey_file: bad base64 decode error

Read on for more details.

Nginx PEM_read_bio_X509: ASN1_CHECK_TLEN:wrong tag error

These kind of errors pop up when your certificate file isn’t valid. The entire error looks like this.

$ service nginx restart

nginx: [emerg] PEM_read_bio_X509("/etc/nginx/ssl/mydomain.tld/certificate.crt") failed (SSL: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:Type=X509_CINF error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:Field=cert_info, Type=X509 error:0906700D:PEM routines:PEM_ASN1_read_bio:ASN1 lib)

You should fix this by beginning to read the SSL certificate info via the CLI. Chances are, OpenSSL will also show you an error, to confirm your SSL certificate isn’t valid.

In the example above, the SSL certificate is in /etc/nginx/ssl/mydomain.tld/certificate.crt, so the following examples continue to use that file.

$ openssl x509 -text -noout -in /etc/nginx/ssl/mydomain.tld/certificate.crt
unable to load certificate
139894337988424:error:0906D064:PEM routines:PEM_read_bio:bad base64 decode:pem_lib.c:818:

If that’s your output, you have confirmation: your SSL certificate is corrupt. It’s got unsupported ASCII characters, it’s missing a part, some copy/paste error caused extra data to be present, … Bottom line: your certificate file won’t work.

You can test a few things yourself, like new line issues (linux vs. windows remains a problem). Open the file in binary mode in vi, and if you see ^M at end of every line, you’ve incorrectly got Windows new lines instead of Unix new lines.

$ vi -b /etc/nginx/ssl/mydomain.tld/certificate.crt
-----BEGIN CERTIFICATE-----^M
MIIFUjCCBDqgAwIBAgIKYsvzdQAAAAAAzTANBgkqhkiG9w0BAQUFADBOMQswCQYD^M
...

Remove all new lines and replace them with “normal” unix new lines (n instead of rn).

If your SSL certificate file contains multiple certificates, like intermediate or CA root certificates, it’s important to check each of them separately. You can check this by counting the «-—-BEGIN CERTIFICATE-—-« lines in the file.

If you’ve got multiple certificates, copy/paste each one to a different file and run the openssl example above. Each should give you valid output from the SSL certificate.

$ grep 'BEGIN CERTIFICATE' /etc/nginx/ssl/mydomain.tld/certificate.crt
-----BEGIN CERTIFICATE-----
-----BEGIN CERTIFICATE-----
-----BEGIN CERTIFICATE-----

The output above shows that the SSL Certificate file contains 3 individual SSL certificates. Copy/paste them all in separate files and validate if they work. If one of them gives you errors, fix that one: find the wrong ASCII characters, fix the new lines, check if you copy/pasted it correctly from your vendor, …

The “nginx: [emerg] PEM_read_bio_X509” error means your Nginx configuration is probably correct, it’s the SSL certificate file itself that is invalid.

Nginx PEM_read_bio_X509_AUX: Expecting: TRUSTED CERTIFICATE

This is an error that is usually resolved very quickly. The certificate file you’re pointing your config to, isn’t a certificate file. At least, not according to Nginx.

$ service nginx configtest

nginx: [emerg] PEM_read_bio_X509_AUX("/etc/nginx/ssl/mydomain.tld/certificate.crt") failed (SSL: error:0906D06C:PEM routines:PEM_read_bio:no start line:Expecting: TRUSTED CERTIFICATE)
nginx: configuration file /etc/nginx/nginx.conf test failed

This can happen if you’ve accidentally swapped your private key and SSL certificate in either your files, or in the Nginx configuration.

Your Nginx config will contain these kind of lines for its SSL configuration.

ssl_certificate             /etc/nginx/ssl/mydomain.tld/certificate.crt;
ssl_certificate_key         /etc/nginx/ssl/mydomain.tld/certificate.key;

Check if the ssl_certificate file is indeed your SSL certificate and if the ssl_certificate_key is indeed your key. It’s not uncommon to mix these up if you’re in a hurry or distracted and save the wrong contents to the wrong file.

Nginx SSL_CTX_use_PrivateKey_file: bad base64 decode error

Another common error in Nginx configurations is the following one.

$ service nginx configtest

nginx: [emerg] SSL_CTX_use_PrivateKey_file("/etc/nginx/ssl/mydomain.tld/certificate.key") failed (SSL: error:0906D064:PEM routines:PEM_read_bio:bad base64 decode error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib)
nginx: configuration file /etc/nginx/nginx.conf test failed

Note how the Nginx SSL error points to the .key file this time. The problem is with the SSL key, not the SSL certificate.

This error indicates that the private key you pointed your configuration to, doesn’t match the SSL Certificate.

You can validate whether private key and SSL certificate match by calculating their MD5 hash. If they don’t match, you have to find either the right certificate or the right private key file.

One of them is wrong and needs to be replaced. With this error, it’s impossible to know which one is wrong. Your best bet is to read the info from the SSL certificate, determine if that’s the correct SSL certificate (check expiration date, SANs, Common Name, …), and find the matching key (which should have been created when you generated your Certificate Signing Request, CSR).

Понравилась статья? Поделить с друзьями:
  • Ssl error no cypher overlap госзакупки
  • Ssl error no cypher overlap zyxel
  • Ssl error no cypher overlap vipnet pki client
  • Ssl error no cypher overlap roskazna
  • Ssl error no cypher overlap firefox как исправить электронный бюджет