How to sign a message with public key RSA - cryptography

I'm new to cryptography and trying to perform simple RSA sign of the message with the public key.
const PublicKey = "-----BEGIN PUBLIC KEY-----GIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCS7h56MiVTsV1SZ9gvWidH5XheZIpq1PUjKA//6m5N5HYkDtWQ9d+jx6niKDRUYf+aVc8StDKvIRJGT2ZZtIJ27FG9VpvZhR5yG38sh51MAPqZ/rpIzXg2Vj9dR2y3IUyWAafJ/VVGlecSYWREK1t6aMi7piHZpP/Rvn+1ImUTQIDAQAB-----END PUBLIC KEY-----"
const MessageKey = "4FSF5BE55B26FBABA402C23E1FF85E8F"
with a help of jsrsasign library I achieved this:
const publicKey = RSA.KEYUTIL.getKey(PublicKey)
const encrypted = RSA.KJUR.crypto.Cipher.encrypt(MessageKey, publicKey, "RSA")
console.log(RSA.hextob64(encrypted))
But I'm afraid it's incorrect. Has someone performed encryption of message with public key in JS?

sign with private key, encrypt with public key
to gen a pub key (with openssl and id_rsa):
openssl rsa -in ~/.ssh/id_rsa -pubout > ~/.ssh/id_rsa.pub.pem
to encrypt:
cat plain.txt | openssl rsautl -encrypt -pubin -inkey ~/.ssh/id_rsa.pub.pem > cipher.txt
to decrypt:
cat cipher.txt | openssl rsautl -decrypt -inkey ~/.ssh/id_rsa

Related

jose-jwt can generate JWT token via private key, but failed to valid token via RSA public key

I was trying to implement JWT authentication based on jose-jwt for .NET, I can generate JWT token by RSA private key successfully, and pass checking on https://jwt.io debugger, but I'm getting stuck on validating the token with RSA public key by the following error message:
RsaUsingSha alg expects key to be of AsymmetricAlgorithm type.
Here is my steps and code snippets:
create PKCS#12 and certificate file
openssl x509 -signkey jwt-auth-private.key -in jwt-auth-csr.csr -req -days 365 -out jwt-auth-certificate.crt
openssl pkcs12 -inkey jwt-auth-private.key -in jwt-auth-certificate.crt -export -CSP "Microsoft Enhanced RSA and AES Cryptographic Provider" -out jwt-auth-pkcs12.pfx
Create JWT token with RSA private key (It works)
var pfxFilePath = string.Format("{0}\\{1}", baseDir, "jwt-auth-pkcs12.pfx");
var cipher = "private-key-cipher";
var privateKey = new X509Certificate2(pfxFilePath, cipher, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider;
var payload = new Dictionary<string, object>()
{
{ "sub", "mr.x#contoso.com" },
{ "exp", 1300819380 }
};
token = Jose.JWT.Encode(payload, privateKey, JwsAlgorithm.RS256);
Valid token with public key (Failed)
var crtFilePath = string.Format("{0}\\{1}", baseDir, "jwt-auth-certificate.crt");
var cipher = "private-key-cipher";
var publicKey = new X509Certificate2(crtFilePath, cipher).GetPublicKey();
var data = Jose.JWT.Decode(token, publicKey);
When I tried to decode token, I got an error message:
RsaUsingSha alg expects key to be of AsymmetricAlgorithm type.
I had no idea on how to find what's wrong, please help. thanks.
Remark: It looks like that the .crt and .pfx file had no issues, cause if I use JWT.NET instead of jose-jwt libs, I can decode the token successfully in the same way.

SSL implementation with Tungstenite: SSL alert number 42

I created a working WebSocket server with async_tungstenite and async_std.
I now want to add SSL using async_native_tls.
If I understood correctly, this crates provides a function accept which takes a TcpStream, handles the TLS handshake and provides a TlsStream<TcpStream> which should behave like a TcpStream but handles the encryption and decryption behind the scene.
To test the server, I created a self-signed certificate.
Based on that, here is how the code handling new TCP connections evolved:
async fn accept_connection(stream: TcpStream, addr: SocketAddr) {
//Websocket stream
let accept_resut = async_tungstenite::accept_async(stream).await;
if let Err(err) = accept_resut {
println!(
"Error while trying to accept websocket: {}",
err.to_string()
);
panic!(err);
}
println!("New web socket: {}", addr);
}
async fn accept_connection(stream: TcpStream, addr: SocketAddr) {
//Open tls certificate !should be done one time and not for each connection!
let file = File::open("identity.pfx").await.unwrap();
let acceptor_result = TlsAcceptor::new(file, "glacon").await;
if let Err(err) = acceptor_result {
println!("Error while opening certificate: {}", err.to_string());
panic!(err);
}
let acceptor = acceptor_result.unwrap();
//Get a stream where tls is handled
let tls_stream_result = acceptor.accept(stream).await;
if let Err(err) = tls_stream_result {
println!("Error during tls handshake: {}", err.to_string());
panic!(err);
}
let tls_stream = tls_stream_result.unwrap();
//Websocket stream
let accept_resut = async_tungstenite::accept_async(tls_stream).await;
if let Err(err) = accept_resut {
println!(
"Error while trying to accept websocket: {}",
err.to_string()
);
panic!(err);
}
println!("New web socket: {}", addr);
}
With this implementation, I now call from a webpage
const sock = new WebSocket('wss://localhost:8020');
This results in the error:
Error while trying to accept websocket:
IO error: error:14094412:SSL routines:ssl3_read_bytes:sslv3 alert bad certificate:../ssl/record/rec_layer_s3.c:1543:SSL alert number 42
thread 'async-std/runtime' panicked at 'Box<Any>', src/main.rs:57:9
It seems like the handshake was successful as the error does not occur during the acceptor.accept. The error states that the certificate is not valid so here is how I created my self-signed certificate.
The openssl version is 1.1.1f
# Create a key
openssl req -nodes -new -key server.key -out server.csr
# Create the self-signed certificate
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
# Convert the certificate to pfx format
openssl pkcs12 -export -out identity.pfx -inkey server.key -in server.crt
I thought that this problem had to do with security feature from the browser as the "SSL alert number 42" seems to come from the client. I tried to disable this option in Firefox settings
Query OCSP responder servers to confirm the current validity of certificates
I also tried to add my server.crt to the Authorities of the certificate manager.
Neither of these worked.
The problem came from the security features of Firefox.
Firefox detects that the certificate is not signed by an authority and sends back an error.
It seems like adding the certificate to the known authorities does not work.
To avoid this issue, I found this thread which indicates that an exception should be added for the address and port of your development Websocket server.
Go to Settings > Certificates > View Certificates > Servers > Add Exception...
Type in your local server (for me localhost:8020).
Add exception.

The remote certificate is invalid according to the validation procedure - NET Core WebAPI

I'm struggling when putting together two ASP.Net Core application talk to each other using HTTPS.
Before setting up the web api, I first generated the HTTPS correspondent certificates through a development private PKI. This is the code to build the client and server certificates. I believe that the PKI part of the code is not relevant for now.
#!/usr/bin/env bash
printf "SET ENVIRONMENT\n\n"
export ca_dir=$HOME/CA
root_ca_config_path=$ca_dir/root-ca/root-ca.conf
sub_ca_config_path=$ca_dir/sub-ca/sub-ca.conf
server_config_path=$ca_dir/server/server_config.conf
client_config_path=$ca_dir/client/client_config.conf
pass=$ca_dir/pass/pass.aes256
printf "CREATED CLIENT FOLDER\n\n"
mkdir -p $ca_dir/client/{certs,private,csr}
printf "CREATED SERIAL\n\n"
openssl rand -hex 16 > $ca_dir/ca-chain/ca-chain.srl
cat << EOF > $server_config_path
basicConstraints = critical, CA:FALSE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always, issuer:always
keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment, keyAgreement
extendedKeyUsage = critical, serverAuth
subjectAltName = #alt_names
[ alt_names ]
# Be sure to include the domain name here because Common Name is not so commonly honoured by itself
DNS.1 = localhost
IP.1 = 127.0.0.1
[ req ]
# Options for the req tool, man req.
default_bits = 2048
distinguished_name = req_distinguished_name
string_mask = utf8only
default_md = sha256
[ req_distinguished_name ]
countryName = BR
stateOrProvinceName = State or Province Name
localityName = Locality Name
0.organizationName = Organization Name
organizationalUnitName = Organization Unit Name
commonName = Common Name
emailAddress = Email Address
countryName_default = BR
stateOrProvinceName_default = Brazil
0.organizationName_default = ElectricStone Ltd
organizationalUnitName_default = FakeProvider
commonName_default = localhost
EOF
cat << EOF > $client_config_path
basicConstraints = critical, CA:FALSE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always, issuer:always
keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = critical, clientAuth
subjectAltName = #alt_names
[ req ]
# Options for the req tool, man req.
default_bits = 2048
distinguished_name = req_distinguished_name
string_mask = utf8only
default_md = sha256
[ req_distinguished_name ]
countryName = BR
stateOrProvinceName = State or Province Name
localityName = Locality Name
0.organizationName = Organization Name
organizationalUnitName = Organization Unit Name
commonName = Common Name
emailAddress = Email Address
countryName_default = BR
stateOrProvinceName_default = Brazil
0.organizationName_default = ElectricStone Ltd
organizationalUnitName_default = eCommerce
commonName_default = localhost
[ alt_names ]
# Be sure to include the domain name here because Common Name is not so commonly honoured by itself
DNS.1 = localhost
IP.1 = 127.0.0.1
EOF
printf "CREATING SERVER PRIVATE KEY...\n\n"
openssl genrsa -out $ca_dir/server/private/netwebapp.key 2048
printf "CREATING CLIENT PRIVATE KEY...\n\n"
openssl genrsa -out $ca_dir/client/private/netwebappclient.key 2048
printf "CREATING A SERVER SIGNING REQUEST...\n\n"
openssl req -config $server_config_path -passin file:$pass -key $ca_dir/server/private/netwebapp.key \
-new -sha256 -out $ca_dir/server/csr/netwebapp.csr
printf "CREATING A CLIENT SIGNING REQUEST...\n\n"
openssl req -config $client_config_path -passin file:$pass -key $ca_dir/client/private/netwebappclient.key \
-new -sha256 -out $ca_dir/client/csr/netwebappclient.csr
printf "CREATING THE SERVER CERTIFICATE...\n\n"
openssl x509 -req -in $ca_dir/server/csr/netwebapp.csr -passin file:$pass \
-CA $ca_dir/ca-chain/ca-chain.crt \
-CAkey $ca_dir/sub-ca/private/sub-ca.key \
-CAserial $ca_dir/ca-chain/ca-chain.srl \
-out $ca_dir/server/certs/netwebapp.crt -days 365 -sha256 -extfile $server_config_path
printf "CREATING THE CLIENT CERTFICATE...\n\n"
openssl x509 -req -in $ca_dir/client/csr/netwebappclient.csr -passin file:$pass \
-CA $ca_dir/ca-chain/ca-chain.crt \
-CAkey $ca_dir/sub-ca/private/sub-ca.key \
-CAserial $ca_dir/ca-chain/ca-chain.srl \
-out $ca_dir/client/certs/netwebappclient.crt -days 365 -sha256 -extfile $client_config_path
After I had generate the certificates I was able to test their effectiveness through respectively openssl commands:
# Testing the server certificate
sudo openssl s_server -accept 443 -www -key $ca_dir/server/private/netwebapp.key \
-CAfile $ca_dir/sub-ca/certs/sub-ca.crt \
-cert $ca_dir/server/certs/netwebapp.crt
# Testing the client certificate
openssl s_client -connect localhost:443 -servername localhost \
-cert /home/dggt/CA/client/certs/netwebappclient.crt \
-key /home/dggt/CA/client/private/netwebappclient.key \
-CAfile /home/dggt/CA/root-ca/certs/ca.crt \
-showcerts
Those test command produced this output at client side:
CONNECTED(00000006)
depth=2 C = BR, ST = Brazil, O = ElectricStone Ltd, CN = ElectricStone Root CA
verify return:1
depth=1 C = BR, ST = Brazil, O = ElectricStone Ltd, CN = ElectricStone SUB CA
verify return:1
depth=0 C = BR, ST = Brazil, O = ElectricStone Ltd, OU = FakeProvider, CN = localhost
verify return:1
---
Certificate chain
0 s:C = BR, ST = Brazil, O = ElectricStone Ltd, OU = FakeProvider, CN = localhost
i:C = BR, ST = Brazil, O = ElectricStone Ltd, CN = ElectricStone SUB CA
-----BEGIN CERTIFICATE-----
################################## Output suppressed ##################################
-----END CERTIFICATE-----
1 s:C = BR, ST = Brazil, O = ElectricStone Ltd, CN = ElectricStone SUB CA
i:C = BR, ST = Brazil, O = ElectricStone Ltd, CN = ElectricStone Root CA
-----BEGIN CERTIFICATE-----
################################## Output suppressed ##################################
-----END CERTIFICATE-----
---
Server certificate
subject=C = BR, ST = Brazil, O = ElectricStone Ltd, OU = FakeProvider, CN = localhost
issuer=C = BR, ST = Brazil, O = ElectricStone Ltd, CN = ElectricStone SUB CA
---
No client certificate CA names sent
Peer signing digest: SHA256
Peer signature type: RSA-PSS
Server Temp Key: X25519, 253 bits
---
SSL handshake has read 3378 bytes and written 381 bytes
Verification: OK
---
New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384
Server public key is 2048 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
---
---
Post-Handshake New Session Ticket arrived:
SSL-Session:
Protocol : TLSv1.3
Cipher : TLS_AES_256_GCM_SHA384
Session-ID: 5D3176780DE3404A9E246E026D875B0B81A3EFE9EB7B2F17D24E3565DB42E1AE
Session-ID-ctx:
Resumption PSK: E9D6B7E66063C4969C203A153A3E60E1131095E2AE1569AE04673BA9F1FA90974ACE42D5B902ABE8A5760218AD2959FF
PSK identity: None
PSK identity hint: None
SRP username: None
TLS session ticket lifetime hint: 7200 (seconds)
TLS session ticket:
################################## Output suppressed ##################################
Start Time: 1605522448
Timeout : 7200 (sec)
Verify return code: 0 (ok)
Extended master secret: no
Max Early Data: 0
---
read R BLOCK
---
Post-Handshake New Session Ticket arrived:
SSL-Session:
Protocol : TLSv1.3
Cipher : TLS_AES_256_GCM_SHA384
Session-ID: 5B8E394EBEBEBC7FD2617EA0695CD9C2E0B8F4ED733F628CA28A5190AB4D27BA
Session-ID-ctx:
Resumption PSK: F536C3428049C2DD6F9496D14E516B30611D2D7056AE6B87445F6328B4B1577093FDA3D4A6AC9D00F30F7725B6925A9E
PSK identity: None
PSK identity hint: None
SRP username: None
TLS session ticket lifetime hint: 7200 (seconds)
TLS session ticket:
################################## Output suppressed ##################################
Start Time: 1605522448
Timeout : 7200 (sec)
Verify return code: 0 (ok)
Extended master secret: no
Max Early Data: 0
---
read R BLOCK
DONE
So far so good. However at ASP.NET Core side the thing get complicated.
Afterwards some research, at one of my API, I configured the built-in Kestrel web server to work with HTTPS by the following code:
Program.cs
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.Https;
using Microsoft.Extensions.Hosting;
namespace BogusProvider
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel((context, options) =>
{
var certificateConfig = context.Configuration.GetSection("Certificate");
var certFileName = certificateConfig["FileName"];
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER")))
{
// Insert a Docker entry coming from user-secrets when development in container
certFileName = certificateConfig["Docker"];
}
var certPassword = certificateConfig["Password"];
// Configure the Url and ports to bind to
// This overrides calls to UseUrls and the ASPNETCORE_URLS environment variable, but will be
// overridden if you call UseIisIntegration() and host behind IIS/IIS Express
// When development in container, use ListenAnyIP method
options.ConfigureHttpsDefaults(adapterOptions =>
{
adapterOptions.CheckCertificateRevocation = false;
adapterOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
});
options.ListenAnyIP(5002, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
listenOptions.UseHttps(certFileName, certPassword);
listenOptions.UseConnectionLogging("FakerHttpsConnection");
});
}).UseStartup<Startup>();
});
}
}
I also installed the Microsoft.AspNetCore.Authentication.Certificate package in order to setup the certificate authentication in the ASP.NET Core machinery.
This is a snippet of code at Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate();
// Others services suppressed
}
With all this code running, I get 'connection refused' when either requesting through the browser (after I have installed the client certificate alongside its private key password and the Sub CA by browser settings) or the other Web API when requesting through HttpClient.
This is my HttpClient code:
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(new X509Certificate2("/home/dggt/CA/client/certs/netwebappclient.pfx",
"pa$$worD_1"));
return new HttpClient(handler) {BaseAddress = new Uri("https://localhost:5002/fake/")};
This the gist of the error message at console:
System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
System Specs:
OS: Ubuntu 20.04
Net Info:
SDK: 3.1.404
Runtime: Microsoft.AspNetCore.App 3.1.10
Any idea of what I might be doing wrong? Any help is welcome!

X509Certificate2 the server mode SSL must use a certificate with the associated private key

I use SslStream to build a web server. However, the code below throws an exception when AuthenticateAsServer.
static X509Certificate cert;
protected virtual Stream GetStream(TcpClient client)
{
var ss = new SslStream(client.GetStream(), false);
if (cert == null)
{
cert = X509Certificate2.CreateFromCertFile("test.cer");
}
ss.AuthenticateAsServer(cert, false, System.Security.Authentication.SslProtocols.Tls, true);
return ss;
}
I've already used X509Certificate2 to load the cert file why it still throw the exception (The server mode SSL must use a certificate with the associated private key)?
The cert file was created using the following command:
makecert
-pe Exportable private key
-n "CN=localhost" Subject name
-ss my Certificate store name
-sr LocalMachine Certificate store location
-a sha1 Signature algorithm
-sky signature Subject key type is for signature purposes
-r Make a self-signed cert
"test.cer" Output filename
makecert.exe -r -pe -n "CN=localhost" -sky exchange -sv server.pvk server.cer
pvk2pfx -pvk server.pvk -spc server.cer -pfx server.pfx -pi <password>
var certificate = new X509Certificate("path\server.pfx", "password");

How to access the client's certificate in Go?

Below is my code for an HTTPS server in Go. The server requires the client to provide an SSL certificate, but doesn't verify the certificate (by design).
You can generate a private/public key pair as follows if you'd like to give it a try:
$ openssl genrsa -out private.pem 2048
$ openssl req -new -x509 -key private.pem -out public.pem -days 365
Does anyone know how I can access the client certificate in the handler? Let's say I would like to report some properties about the certificate the client presented back to the client.
Thanks,
Chris.
package main
import (
"fmt"
"crypto/tls"
"net/http"
)
const (
PORT = ":8443"
PRIV_KEY = "./private.pem"
PUBLIC_KEY = "./public.pem"
)
func rootHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Nobody should read this.")
}
func main() {
server := &http.Server{
TLSConfig: &tls.Config{
ClientAuth: tls.RequireAnyClientCert,
MinVersion: tls.VersionTLS12,
},
Addr: "127.0.0.1:8443",
}
http.HandleFunc("/", rootHandler)
err := server.ListenAndServeTLS(PUBLIC_KEY, PRIV_KEY)
if err != nil {
fmt.Printf("main(): %s\n", err)
}
}
Seems r *http.Request has TLS *tls.ConnectionState field which in turn has PeerCertificates []*x509.Certificate field, so
fmt.Fprint(w, r.TLS.PeerCertificates)
probably can do