본문 바로가기

Web Frontend/Vue

[Javascript] Query String 암호화하기 - crypto-js

728x90

URL을 통해 data를 넘겨줄 때 암호화를 하지 않으면 만천하에 중요한 data를 노출하게 되기 때문에 중요한 내용을 넘겨야 하는 경우 반드시 암호화를 해줘야 한다. 백엔드가 있는 경우 백엔드 내부적으로 암호화 해주는 코드를 작성하면 되는데, 프론트엔드만 사용하는 경우 crypto-js를 사용하면 간단하게 해결할 수 있다.
crypto-js 공식 페이지는 다음과 같다.
crypto-js - npm (npmjs.com)

 

crypto-js

JavaScript library of crypto standards.. Latest version: 4.2.0, last published: a month ago. Start using crypto-js in your project by running `npm i crypto-js`. There are 10945 other projects in the npm registry using crypto-js.

www.npmjs.com

우선 crypto-js를 설치해보자

npm install crypto-js

아래와 같이 encryptData 함수를 작성하면 되는데
encryptData는 data를 받아서 string으로 바꾸고
string을 key를 이용해서 encode한 후
다시 string으로 바꿔주는 함수이다.

import router from "../router/index.js";
import cryptoJs from "crypto-js";
import { randomKey } from "@/main";

export default {
  setup() {
    const score = ref(0);
    const timer = ref(0);

	// score, timer 올라가는 코드

    const encryptData = (data) => {
      const textToEncrypt = JSON.stringify(data);
      const encryptedData = cryptoJs.AES.encrypt(
        textToEncrypt,
        randomKey
      ).toString();
      return encryptedData;
    };
    
    router.push({
      path: "/result",
      query: {
        score: encryptData(score.value),
        timer: encryptData(timer.value),
      },
    });
  },
};

encoding하는 과정에서는 AES 암호 체계를 사용하는 것을 알 수 있다. 필자의 경우 key는 randomKey를 사용했는데 key가 항상 동일하면 encoding을 해도 같은 값이 나오기 때문에 매번 key를 random하게 만들어서 encoding, decoding할 때 같은 key를 사용하게끔 했다.

https://fourlettersquizz.web.app/result?score=U2FsdGVkX1/TcwaKyfjaXrU7YSAi2wHCc8C177Suzvc=&timer=U2FsdGVkX19t896V3mPCKSB2en40dlwzPnfxpqCB99I=

위와 같이 score과 timer에 어마어마한 string이 들어가 있는 것을 알 수 있다. 위의 값들이 encryptData("10") 그리고 encryptData("13.57")의 결과라고 생각하면 된다.
encrypt를 했으면 data를 사용하기 위해서는 decrypt 해줘야 한다.

import { useRoute } from "vue-router";
import cryptoJs from "crypto-js";
import { randomKey } from "@/main";

export default {
  setup() {
    const decryptData = (encryptedData) => {
      const bytes = cryptoJs.AES.decrypt(encryptedData, randomKey);
      const decryptedData = bytes.toString(cryptoJs.enc.Utf8);
      return decryptedData;
    };
    
    const route = useRoute();
    const score = decryptData(route.query.score);
    const timer = decryptData(route.query.timer);
  },
};

위 code에서 보면 마찬가지로 동일한 key를 사용하여 AES 암호체계로 decrypt한 후 string으로 바꿔서 반환하는 것을 볼 수 있다. 이처럼 crypto-js package를 사용하면 URL을 통해 데이터를 주고 받을 때 민감한 정보가 노출되는 것을 방지할 수 있다. 

export const randomKey = (Math.floor(Math.random() * 90000) + 10000).toString();

참고로 main.js에서는 위와 같이 랜덤으로 5자리 숫자를 만들어서 문자열로 바꾸고 randomKey를 export 하였고, 이를 import하여 encrypt, decrypt 과정에서 key로 사용했다. 

728x90

'Web Frontend > Vue' 카테고리의 다른 글

[Vue] 프로젝트 시작하기  (1) 2023.12.07
[Javascript] URL query string  (0) 2023.12.05
[Javascript] 네 글자 퀴즈 - Vue3 Project  (2) 2023.12.04