RSA SubtleCrypto

Aiden·2022년 5월 25일
0

타입스크립트에서 crypto 모듈이 임포드가 안되는 현상이 발생하였음.
백엔드에서 OAEPPadding으로 암호화 하기를 요구.
이러한 복합적인 상황이 발생하여서 직접 암호화를 하기로 결정.
될 수 있으면 라이브러리를 사용하십시오.

ArrayBuffer
ArrayBuffer는 바이트로 구성된 배열로, 다른 언어에서는 종종 "바이트 배열"이라고 부릅니다. ArrayBuffer에 담긴 정보를 직접 수정하는 것은 불가능하지만, 대신 형식화 배열이나 DataView 객체를 통해 버퍼를 특정 형식으로 나타내고, 이를 통해 버퍼의 내용을 읽거나 쓸 수 있습니다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer

데이터를 넣을때 ArrayBuffer 형태로 넣어야한다. return값도 ArrayBuffer로 나온다.
key는 받아서 CryptoKey형태로 넣어야된다.

function str2ab(str: any) {
    const buf = new ArrayBuffer(str.length);
    const bufView = new Uint8Array(buf);
    for (let i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return buf;
  }

  const pemEncodedKey = `-----BEGIN PUBLIC KEY-----
  -----END PUBLIC KEY-----`;

  function importRsaKey(pem: any) {
    // fetch the part of the PEM string between header and footer
    const pemHeader = "-----BEGIN PUBLIC KEY-----";
    const pemFooter = "-----END PUBLIC KEY-----";
    const pemContents = pem.substring(
      pemHeader.length,
      pem.length - pemFooter.length
    );
    // base64 decode the string to get the binary data
    const binaryDerString = window.atob(pemContents);
    // convert from a binary string to an ArrayBuffer
    const binaryDer = str2ab(binaryDerString);

    return window.crypto.subtle.importKey(
      "spki",
      binaryDer,
      {
        name: "RSA-OAEP",
        hash: "SHA-1",
      },
      true,
      ["encrypt"]
    );
  }

  async function encryptMessage(publicKey: any) {
    const data = str2ab(jsonData);
    const ciphertext = await importRsaKey(publicKey);
    return window.crypto.subtle.encrypt(
      {
        name: "RSA-OAEP",
      },
      ciphertext,
      data
    );
  }
   const encryptData = await encryptMessage(pemEncodedKey);

  function importPrivateRsaKey(pem: any) {
    // fetch the part of the PEM string between header and footer
    const pemHeader = "-----BEGIN PRIVATE KEY-----";
    const pemFooter = "-----END PRIVATE KEY-----";
    const pemContents = pem.substring(
      pemHeader.length,
      pem.length - pemFooter.length
    );
    // base64 decode the string to get the binary data
    const binaryDerString = window.atob(pemContents);
    // convert from a binary string to an ArrayBuffer
    const binaryDer = str2ab(binaryDerString);

    return window.crypto.subtle.importKey(
      "pkcs8",
      binaryDer,
      {
        name: "RSA-OAEP",
        hash: "SHA-1",
      },
      true,
      ["decrypt"]
    );
  }
  const privateKey = `-----BEGIN PRIVATE KEY-----
  -----END PRIVATE KEY-----`;
  async function decryptMessage(ciphertext: any) {
    const pk = await importPrivateRsaKey(privateKey);
    return window.crypto.subtle.decrypt(
      {
        name: "RSA-OAEP",
      },
      pk,
      ciphertext
    );
  }
  const decryptData = await decryptMessage(encryptData); 
  
  

참고 https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto

MDN은 신이다

0개의 댓글