ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 문자열 암호화 / 복호화 with Python
    Programming Language/Python 2021. 2. 1. 18:44
    반응형
    • 문자열을 네트워크를 통해 주고 받을 때 위험성
      • 문자열을 누군가가 탈취 할 수 있다.
      • 탈취된 문자열을 기반으로 임의의 수정을 하여 시스템에 문제를 야기 할 수 있다.
    • 암호화 / 복호화를 통해 문자열(data)로 인한 위험성을 줄일 수 있다.

    1. rsa 키 생성

    openssl 명령어를 이용해서 rsa private/public key 생성

    • generate private key
    $ openssl genrsa -out private.pem 4096
    Generating RSA private key, 4096 bit long modulus (2 primes)
    ......................++++
    ...........................++++
    e is 65537 (0x010001)
    
    $ ls -l private.pem
    -rw------- 1 root root 3243  2월  1 18:07 private.pem
    
    $ head -n 2 private.pem
    -----BEGIN RSA PRIVATE KEY-----
    MIIJJwIBAAKCAgEA27Btqh0ahq3+XHYtIy+7k+BYcfeDnScMuk1O26xvqHjfrPi0
    • generate public key
    $ openssl rsa -in private.pem -out public.pem -pubout
    writing RSA key
    
    $ ls -l public.pem
    -rw-r--r-- 1 root root 800  2월  1 18:12 public.pem
    
    $ head -n 2 public.pem
    -----BEGIN PUBLIC KEY-----
    MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA27Btqh0ahq3+XHYtIy+7

    2. encrypt code

    • this is a message for encrypting 라는 메세지를 암호화 하여, 암호화된 string 을 가져오는 코드
    import base64  # string 데이터를 encode / decode 하기 위한 라이브러리
    import rsa  # rsa 모듈을 이용해서 메세지를 암호화 할 것
    
    msg = "this is a message for encrypting"
    msg = msg.encode('utf-8')  # 공개키로 암호화를 하기 위해 str -> bytes 형태로 변경
    
    public_key_bytes = open('public.pem', 'rb').read()  # 공개키 파일을 읽기
    public_key = rsa.PublicKey.load_pkcs1_openssl_pem(keyfile=public_key_bytes)  # 공개키 파일을 이용해서 공개키로 변환
    print(public_key)
    """
    PublicKey(8962536328556741752138...959490690096857894591, 65537)
    """
    
    encrypted_bytes = rsa.encrypt(msg, public_key)  # 공개키를 이용해서 암호화
    print(encrypted_bytes)
    """
    b'\x0e,\x1e\xb8=...8by\xbd[I*=Jg'
    """
    
    encrypted_msg = base64.b64encode(encrypted_bytes).decode('utf-8')  # 암호화된 bytes 데이터를 string 형태로 decode
    print(encrypted_msg)
    """
    DiweuD267Lx8ZblNMeP...bSSo9Smc=
    """

    3. decrypt code

    • 암호화된 string 을 복호화 하여 this is a message for encrypting 메세지를 가져오는 코드
    import base64  # string 데이터를 encode / decode 하기 위한 라이브러리
    import rsa  # rsa 모듈을 이용해서 메세지를 암호화 할 것
    
    encrypted_msg = 'DiweuD267Lx8ZblNMeP...bSSo9Smc='
    encoded_msg = base64.b64decode(encrypted_msg)  # string -> bytes 로 인코딩
    print(encoded_msg)
    """
    b'\x0e,\x1e\xb8=...8by\xbd[I*=Jg'
    """
    
    private_key_bytes = open('private.pem', 'rb').read()
    private_key = rsa.PrivateKey.load_pkcs1(keyfile=private_key_bytes)
    print(private_key)
    """
    PrivateKey(896253632855...53261438150234649793)
    """
    
    msg = rsa.decrypt(encoded_msg, private_key).decode('utf-8')
    print(msg)
    """
    this is a message for encrypting
    """
    반응형

    댓글

Designed by Tistory.