Node.js crypto 모듈 사용해보기
2018-11-11 21:13:18

sha512

주로 유저 비밀번호 저장할 떄 사용, 단방향이라서 복호화를 할 수 업음.

1
2
3
4
5
6
7
8
9
10
const crypto = require('crypto');

const key = 'delryn';

/**
* TODO: sha512 해싱 알고리즘
* @description 단방향
* @param {String} text 암호화할 평문.
*/
const sha512 = (text) => crypto.createHash('sha512').update(key + text).digest('base64');

hmac

주로 웹 api 통신할 때 사용자 검증으로 사용, 복호화 불가

1
2
3
4
5
6
7
8
9
10
const crypto = require('crypto');

const key = 'delryn';

/**
* TODO: hmac 해싱 알고리즘
* @description 단방향
* @param {String} text 암호화할 평문
*/
const hmac = (text) => crypto.createHmac('sha256', key).update(text).digest('hex');

aes256

웹 api 통신에서 암호화하여 전송 -> 받는 쪽은 복호화해서 사용

서로 키가 달라지면 안됨, 키의 길이 조건보다 낮으면 불가함

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const crypto = require('crypto');

// TODO: aes256 key 만들기 16byte
const makeAes256Key = crypto.randomBytes(16).toString('hex');

// TODO: aes256 iv 만들기 8byte
const makeIv = crypto.randomBytes(8).toString('hex');

/**
* TODO: AES 256 암호화
* @description 양방향
* @param {*} aesKey aes256 key
* @param {*} aesIv aes256 IV
* @param {*} text 암호화할 평문
*/
const aes256Encrypt = (aesKey, aesIv, text) => {
try {
const cipher = crypto.createCipheriv('aes-256-cbc', aesKey, aesIv);
let result = cipher.update(text, 'utf8', 'base64');
result += cipher.final('base64');
return result;
} catch (error) {
return error;
}
};

/**
* TODO: AES 256 복호화
* @description 양방향
* @param {*} aesKey aes256 key
* @param {*} aesIv aes256 IV
* @param {*} cryptogram 암호문
*/
const aes256Decrypt = (aesKey, aesIv, cryptogram) => {
try {
const decipher = crypto.createDecipheriv('aes-256-cbc', aesKey, aesIv);
let result = decipher.update(cryptogram, 'base64', 'utf8');
result += decipher.final('utf8');
return result;
} catch (error) {
return error;
}
};
Prev
2018-11-11 21:13:18
Next