HTTPS
Hyper Text Transfer Protocol Secure
HTTP요청을 SSL/TLS라는 알고리즘을 이용해 HTTP 통신을 하는 과정에서 내용을 암호화하여 데이터를 전송하는 방법
*여기서 메시지는 요청, 응답 둘 다 의미
원리
두개의 키가 하나의 쌍으로 존재하고, 하나로 암호화를 했다면 다른 하나로 복호화해야한다. 따라서 복호화하는 키는 비밀로 숨겨두고, 암호화하는 키는 클라이언트에 공개해서 데이터를 안전하게 전송한다.
하지만, 클라이언트와 서버가 모든 통신을 비대칭키로 하면 서버에 부담이 되기 때문에, 인증서를 확인하는 과정에서 공개키를 사용하고, 이후 생성된 임시키(비밀키)로 대칭키 키 암호화를 사용한다.
통신과정
//Ubuntu mkcert 설치하기
$ sudo apt install libnss3-tools
$ wget -O mkcert https://github.com/FiloSottile/mkcert/releases/download/v1.4.3/mkcert-v1.4.3-linux-amd64
$ chmod +x mkcert
$ sudo cp mkcert /usr/local/bin/
//macOS
$ brew install mkcert
# firefox를 사용할 경우 필요에 따라 설치해주세요.
$ brew install nss
//인증서 생성
//로컬을 인증된 발급기관으로 추가한다
$ mkcert -install
//localhost로 대표되는 로컬 환경에 대한 인증서를 만든다
$ mkcert -key-file key.pem -cert-file cert.pem localhost 127.0.0.1 ::1
//옵션으로 추가한 localhost, 127.0.0.1(IPv4), ::1(IPv6)에서 사용할 수 있는 인증서 완성. cert.pem, key.pem 이라는 파일이 생성된 것을 확인가능.
//key.pem의 경우 개인 키이므로 git에 커밋하지 않고, 암호처럼 다루어야 합니다.
//HTTP 서버작성
//node.js https 모듈 이용
const https = require('https');
const fs = require('fs');
https
.createServer(
{
key: fs.readFileSync(__dirname + '/key.pem', 'utf-8'),
cert: fs.readFileSync(__dirname + '/cert.pem', 'utf-8'),
},
function (req, res) {
res.write('Congrats! You made https server now :)');
res.end();
}
)
.listen(3001);
//express.js 이용
const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();
https
.createServer(
{
key: fs.readFileSync(__dirname + '/key.pem', 'utf-8'),
cert: fs.readFileSync(__dirname + '/cert.pem', 'utf-8'),
},
app.use('/', (req, res) => {
res.send('Congrats! You made https server now :)');
})
)
.listen(3001);
//서버실행 후 https://localhost:3001로 접속시 url 왼쪽에 자물쇠가 생긴 HTTPS 프로토콜 이용한다는 것을 알 수 있다