Microsoft MVP성태의 닷넷 이야기
닷넷: 2203. C# - Python과의 AES 암호화 연동 [링크 복사], [링크+제목 복사],
조회: 9864
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 2개 있습니다.)
.NET Framework: 847. JAVA와 .NET 간의 AES 암호화 연동
; https://www.sysnet.pe.kr/2/0/11972

닷넷: 2203. C# - Python과의 AES 암호화 연동
; https://www.sysnet.pe.kr/2/0/13530




C# - Python과의 AES 암호화 연동

간단하게, Python으로는 이렇게 암호화/복호화를 할 수 있고,

# 패키지 2개 설치
# pip install pycryptodome
# pip install pycryptodomex

from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad, pad

iv = "0123456789abcdef"
key = "abcdefghijklmnopabcdefghijklmnop"

cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))

data = "test is good, not bad, so so.".encode('utf-8')
padded_data = pad(data, AES.block_size)  # AES.block_size == 16
encrypted_data = cipher.encrypt(padded_data)

with open('encrypted.bin', 'wb') as f:
    f.write(encrypted_data)

# 복호화
# cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))

# decrypted_data = cipher.decrypt(encrypted_data)
# unpadded_data = unpad(decrypted_data, AES.block_size)
# print(bytes.decode(unpadded_data))

위의 코드로 저장한 encrypted.bin 파일을 C#에서 복호화 하려면 다음과 같이 코딩할 수 있습니다.

using System.Security.Cryptography;
using System.Text;

namespace ConsoleApp1;

internal class Program
{
    static void Main(string[] args)
    {
        byte[] iv = Encoding.UTF8.GetBytes("0123456789abcdef"); // 파이썬에서 사용한 iv와 동일
        byte[] key = Encoding.UTF8.GetBytes("abcdefghijklmnopabcdefghijklmnop"); // 파이썬에서 사용한 key와 동일
        byte[] encrypted_data = File.ReadAllBytes("encrypted.bin");

        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = key;
            aesAlg.IV = iv;

            Console.WriteLine($"BlockSize: {aesAlg.BlockSize}(bits) {aesAlg.BlockSize / 8}(bytes)"); // 기본값이 파이썬의 BlockSize와 동일
            Console.WriteLine($"Mode: {aesAlg.Mode}"); // 기본값이 CBC

            var decryptor = aesAlg.CreateDecryptor();
            using (var ms = new MemoryStream(encrypted_data))
            using (var decrypt = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
            using (var plain = new MemoryStream())
            {
                decrypt.CopyTo(plain);
                string text = Encoding.UTF8.GetString(plain.GetBuffer(), 0, (int)plain.Length);
                Console.WriteLine(text); // 출력 결과: test is good, not bad, so so
            }
        }
    }
}

마찬가지로, C#으로 Encrypt, 파이썬에서 Decrypt하는 것도 위의 옵션 그대로 사용해 과정만 역으로 하면 됩니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 1/15/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12685정성태6/21/202118094Java: 21. Azure Web App Service에 배포된 Java 프로세스의 메모리 및 힙(Heap) 덤프 뜨는 방법
12684정성태6/19/202116438오류 유형: 728. Visual Studio 2022부터 DTE.get_Properties 속성 접근 시 System.MissingMethodException 예외 발생
12683정성태6/18/202117757VS.NET IDE: 166. Visual Studio 2022 - Windows Forms 프로젝트의 x86 DLL 컨트롤이 Designer에서 오류가 발생하는 문제 [1]파일 다운로드1
12682정성태6/18/202114309VS.NET IDE: 165. Visual Studio 2022를 위한 Extension 마이그레이션
12681정성태6/18/202114564오류 유형: 727. .NET 2.0 ~ 3.5 + x64 환경에서 System.EnterpriseServices 참조 시 CS8012 경고
12680정성태6/18/202116608오류 유형: 726. python2.7.exe 실행 시 0xc000007b 오류
12679정성태6/18/202116752COM 개체 관련: 23. CoInitializeSecurity의 전역 설정을 재정의하는 CoSetProxyBlanket 함수 사용법파일 다운로드1
12678정성태6/17/202115263.NET Framework: 1072. C# - CoCreateInstance 관련 Inteop 오류 정리파일 다운로드1
12677정성태6/17/202118043VC++: 144. 역공학을 통한 lxssmanager.dll의 ILxssSession 사용법 분석파일 다운로드1
12676정성태6/16/202117226VC++: 143. ionescu007/lxss github repo에 공개된 lxssmanager.dll의 CLSID_LxssUserSession/IID_ILxssSession 사용법파일 다운로드1
12675정성태6/16/202115099Java: 20. maven package 명령어 결과물로 (war가 아닌) jar 생성 방법
12674정성태6/15/202116364VC++: 142. DEFINE_GUID 사용법
12673정성태6/15/202116972Java: 19. IntelliJ - 자바(Java)로 만드는 Web App을 Tomcat에서 실행하는 방법
12672정성태6/15/202118569오류 유형: 725. IntelliJ에서 Java webapp 실행 시 "Address localhost:1099 is already in use" 오류
12671정성태6/15/202127241오류 유형: 724. Tomcat 실행 시 Failed to initialize connector [Connector[HTTP/1.1-8080]] 오류
12670정성태6/13/202117216.NET Framework: 1071. DLL Surrogate를 이용한 Out-of-process COM 개체에서의 CoInitializeSecurity 문제파일 다운로드1
12669정성태6/11/202117400.NET Framework: 1070. 사용자 정의 GetHashCode 메서드 구현은 C# 9.0의 record 또는 리팩터링에 맡기세요.
12668정성태6/11/202119912.NET Framework: 1069. C# - DLL Surrogate를 이용한 Out-of-process COM 개체 제작파일 다운로드2
12667정성태6/10/202117720.NET Framework: 1068. COM+ 서버 응용 프로그램을 이용해 CoInitializeSecurity 제약 해결파일 다운로드1
12666정성태6/10/202115347.NET Framework: 1067. 별도 DLL에 포함된 타입을 STAThread Main 메서드에서 사용하는 경우 CoInitializeSecurity 자동 호출파일 다운로드1
12665정성태6/9/202117403.NET Framework: 1066. Wslhub.Sdk 사용으로 알아보는 CoInitializeSecurity 사용 제약파일 다운로드1
12664정성태6/9/202115172오류 유형: 723. COM+ PIA 참조 시 "This operation failed because the QueryInterface call on the COM component" 오류
12663정성태6/9/202117602.NET Framework: 1065. Windows Forms - 속성 창의 디자인 설정 지원: 문자열 목록 내에서 항목을 선택하는 TypeConverter 제작파일 다운로드1
12662정성태6/8/202115357.NET Framework: 1064. C# COM 개체를 PIA(Primary Interop Assembly)로써 "Embed Interop Types" 참조하는 방법파일 다운로드1
12661정성태6/4/202127347.NET Framework: 1063. C# - MQTT를 이용한 클라이언트/서버(Broker) 통신 예제 [4]파일 다운로드1
12660정성태6/3/202118077.NET Framework: 1062. Windows Forms - 폼 내에서 발생하는 마우스 이벤트를 자식 컨트롤 영역에 상관없이 수신하는 방법 [1]파일 다운로드1
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...