본문 바로가기
coding/react native

[React Native] 로컬저장소의 데이터를 받아서 암호화하기

by 코딩희송 2021. 4. 15.

coding-heesong.tistory.com/10

 

[React Native/JS] CryptoJS AES 실무에서 사용하기

리액트 네이티브에서 cryptojs 사용하기 plan text , clear text : 원래 값 encrypt , cipher text : 암호화 decrypt : 복호화 복호화는 암호화의 역과정. (즉 암호화를 풀어서 plan text로 읽히게 해주는 것) 설..

coding-heesong.tistory.com

1. 첫 페이지 로드시 로컬스토리지 값이 있나 없나 체크 하는 init() 함수 만들기

2. 조건 충족 시 handleSubmit 이벤트핸들러 동작 시키기

 


1.

useEffect(()=>{
    init();
}, [])
const init = async () => {
    const ciphertext = await AsyncStorage.getItem("@Bank");
    // 로컬스토리지 값 체크
    if(ciphertext != null) {
        // 값이 있으면 복호화해서 저장
        const bytes = CryptoJS.AES.decrypt(ciphertext, BANK_KEY); // BANK_KEY는 상수로 담겨있다.
        const originaltext = bytes.toString(CryptoJS.enc.Utf8);

        // 복호화한 값을 객체에 저장
        const { bankAccountNo, bankName, bankOwner } = JSON.parse(originalText);

        // 스테이트 값 업데이트
        setReceivingInsurance({ bankAccountNo, bankName, bankOwner });

        // 변경되었다고 알려주기 추후 handleSubmit에서 변경 감지에 사용됨
        setChecked(true);
    }
}

2.

const handleSubmit = async () => {
  if (checked) { // 스테이트 값이 업데이트 되었다면
    // 값을 다시 암호화해서
    const ciphertext = CryptoJS.AES.encrypt(JSON.stringify(receivingInsurance), BANK_KEY).toString();

    // 앱 로컬스토리지에 다시 저장한다.
    await AsyncStorage.setItem('@Bank', ciphertext);
  }

  // 전역 상태 관리 값에도 값을 넣어서 전체적으로 관리해준다.
  claimRequestVar({ ...claimRequest, receivingInsurance: { ...claimRequest.receivingInsurance, ...receivingInsurance } });

  // 완료 되었으면 라우터 이동
  navigation.navigate('다음페이지');
};

댓글