How can I set up a letsencrypt SSL certificate and use it in a https server in dart?

651 views Asked by At

I try:

import 'dart:io';
import "dart:isolate";
main() {
    SecurityContext context = new SecurityContext();
    var chain = Platform.script.resolve('/etc/letsencrypt/live/example.com/chain.pem').toFilePath();
    var key = Platform.script.resolve('/etc/letsencrypt/live/example.com/privkey.pem').toFilePath();
    context.useCertificateChain(chain);
    // context.usePrivateKey(key, password: '?????');
    context.usePrivateKey(key);

    HttpServer.bindSecure(InternetAddress.ANY_IP_V4, 443, context).then((server) {
        server.listen((HttpRequest request) {
            request.response.write('Hello, world!');
            request.response.close();
        });
    });
}

But not work! Any ideas to make this work? https://api.dartlang.org/stable/1.24.2/dart-io/HttpServer-class.html#id_bindSecure

Error Message:

Unhandled exception:
TlsException: Failure in usePrivateKeyBytes (OS Error: 
    KEY_VALUES_MISMATCH(x509_cmp.c:331), errno = 0)
#0      _SecurityContext.usePrivateKeyBytes (dart:io-patch/secure_socket_patch.dart:156)
#1      _SecurityContext.usePrivateKey (dart:io-patch/secure_socket_patch.dart:152)
#2      main (file:///usr/local/www/www.revisortextos.pt/bin/main.dart:2105:10)
<asynchronous suspension>
#3      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:263)
#4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:151)
1

There are 1 answers

1
hdias On

I found the solution to the problem:

import 'dart:io';
import "dart:isolate";

main() {
    SecurityContext context = new SecurityContext();
    var chain = Platform.script.resolve('/etc/letsencrypt/live/www.example.com/fullchain.pem').toFilePath();
    var key = Platform.script.resolve('/etc/letsencrypt/live/www.example.com/privkey.pem').toFilePath();
    context.useCertificateChain(chain);
    // Password not Required
    context.usePrivateKey(key);

    HttpServer.bindSecure(InternetAddress.ANY_IP_V4, 443, context).then((server) {
        server.listen((HttpRequest request) {
            request.response.write('Hello, world!');
            request.response.close();
        });
    });
}

$ wget https://www.example.com/
--2017-10-31 14:51:29--  https://www.example.com/
Loaded CA certificate '/etc/ssl/certs/ca-certificates.crt'
Resolving www.example.com... xxx.xxx.xxx.xxx
Connecting to www.example.com|xxx.xxx.xxx.xxx|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: ‘index.html’

index.html                  [ <=>                            ]   5.06K  --.-KB/s    in 0s      

2017-10-31 14:51:31 (11.2 MB/s) - ‘index.html’ saved [20589]