crypto-js 암호화,복호화하기
개요
crypto는 암호화 모듈이다.
특히 사용자의 패스워드를 평문 그대로 DB에 담아놓으면 보안에 굉장히 취약해지고,
클라이언트가 서버에 패스워드를 전송할 때 또 한 위험에 노출된다.
crypto를 통해 텍스트를 암호화하고, 비교하는법을 알아보자.
그전에 앞서 암호화에 대해 간단히 알아보자.
단방향 암호화, 양방향 암호화
단방향은 암호화가 진행된 문자를 복호화할 수 없음을 말한다.
양방향은 암호화가 진행된 문자를 다시 복호화하여 문자를 풀어낼 수 있다.
단방향 암호화는 Hash 알고리즘을 사용한다.
양방향 암호화는 3DES, AES, RSA 알고리즘을 사용한다.
Hash 함수 알고리즘
임의의 길이의 데이터를 고정된 길이의 데이터로 매핑하는 함수다.
Hash 알고리즘의 종류는 MD5, SHA 등이 있다.
예를들어 "AB" 나 "ABCDE"를 암호화할 때 알고리즘의 길이를 3으로 설정한다면 "qw3" "g2r"처럼
고정된 길이의 결과값이 나오며, 길이가 길수록 보안이 강해진다.
대칭키 비대칭키
대칭키란 암호화 - 복호화를 할 때 같은 키 값을 이용하는 것
대칭키를 사용하는 알고리즘 종류는 DES, 3-DES, AES, SEED, ARIA
비대칭키란 암호화 - 복호화를 할 때 다른 키 값을 이용하는 것
비대칭키를 사용하는 알고리즘 종류는 RSA, ECC, DSS
crypto 설치
npm이나 yarn을 통해 모듈을 설치해줄 수 있다.
npm install crypto-js
yarn add crypto-js
Hash와 AES 알고리즘
import CryptoJS from "crypto-js";
const Encryption = () => {
var password = "sungtt"
//Hash
var Hash = CryptoJS.SHA256(password)
var HashBase = Hash.toString(CryptoJS.enc.Base64)
// Encrypt
var ciphertext = CryptoJS.AES.encrypt(password, 'secret key 123').toString();
// Decrypt
var bytes = CryptoJS.AES.decrypt(ciphertext, 'secret key 123');
var originalText = bytes.toString(CryptoJS.enc.Utf8);
console.log(Hash)
console.log(HashBase)
console.log(ciphertext)
console.log(bytes)
console.log(originalText); // 'my message'
return(
<div>
<p>Hash 암호화된 값:{HashBase}</p>
<p>AES 암호화된 값:{ciphertext}</p>
<p>AES 복호화된 값:{originalText}</p>
</div>
)
}
export default Encryption;
위의 과정들을 콘솔로그로 확인해보면 아래와 같다.
https://cryptojs.gitbook.io/docs/
CryptoJS - CryptoJS
For the ciphertext, the cipher algorithms accept either strings or instances of CryptoJS.lib.CipherParams. A CipherParams object represents a collection of parameters such as the IV, a salt, and the raw ciphertext itself. When you pass a string, it's autom
cryptojs.gitbook.io