Programing

공개 키를 사용하여 openssl에서 대용량 파일을 암호화하는 방법

lottogame 2020. 11. 3. 07:37
반응형

공개 키를 사용하여 openssl에서 대용량 파일을 암호화하는 방법


개인 키를 가진 사람 외에 다른 사람이 해독 할 수 없도록 공개 키로 대용량 파일을 암호화하려면 어떻게해야합니까?

RSA 공개 및 개인 키를 만들 수 있지만 다음 명령을 사용하여 대용량 파일을 암호화 할 때 :

openssl rsautl -encrypt -pubin -inkey public.pem -in myLargeFile.xml -out myLargeFile_encrypted.xml

그리고 어떻게 해독을 수행 할 수 있습니까? ...

다음 명령으로 개인 및 공개 키를 만듭니다.

openssl genrsa -out private.pem 1024
openssl rsa -in private.pem -out public.pem -outform PEM -pubout

이 오류가 발생합니다.

RSA operation error
3020:error:0406D06E:rsa routines:RSA_padding_add_PKCS1_type_2:data too large for key size:.\crypto\rsa\rsa_pk1.c:151:

나는 1024 비트에서 1200 비트 사이의 크기로 키를 만들려고했지만 운이없고 동일한 오류


공개 키 암호화는 임의의 긴 파일을 암호화하기위한 것이 아닙니다. 하나는 대칭 암호 (예 : AES)를 사용하여 일반 암호화를 수행합니다. 새로운 무작위 대칭 키가 생성되고 사용 된 다음 RSA 암호 (공개 키)로 암호화 될 때마다. 암호화 된 대칭 키와 함께 암호문이 수신자에게 전송됩니다. 받는 사람은 개인 키를 사용하여 대칭 키를 해독 한 다음 대칭 키를 사용하여 메시지를 해독합니다.

개인 키는 공유되지 않으며 임의의 대칭 암호를 암호화하는 데 공개 키만 사용됩니다.


OpenSSL 및 명령 줄에서 모든 파일을 안전하고 높은 보안으로 인코딩하는 솔루션 :

PEM 형식으로 파일을 암호화하려면 X.509 인증서를 준비해야합니다.

파일 암호화 :

openssl smime -encrypt -binary -aes-256-cbc -in plainfile.zip -out encrypted.zip.enc -outform DER yourSslCertificate.pem

무엇입니까 :

  • smime -S / MIME 유틸리티 용 ssl 명령 ( smime (1) )
  • -encrypt- 파일 처리를 위해 선택한 방법
  • -binary- 안전한 파일 프로세스를 사용합니다. 일반적으로 입력 메시지는 S / MIME 사양에 따라 "표준"형식으로 변환되며이 스위치는이를 비활성화합니다. 모든 바이너리 파일 (예 : 이미지, 사운드, ZIP 아카이브)에 필요합니다.
  • -aes-256-cbc- 암호화를 위해 256 비트에서 선택한 암호 AES (강력 함). 지정하지 않으면 40 비트 RC2가 사용됩니다 (매우 약함). ( 지원되는 암호 )
  • -in plainfile.zip- 입력 파일 이름
  • -out encrypted.zip.enc- 출력 파일 이름
  • -outform DER- 출력 파일을 바이너리로 인코딩합니다. 지정하지 않으면 파일이 base64로 인코딩되고 파일 크기가 30 % 증가합니다.
  • yourSslCertificate.pem- 인증서의 파일 이름입니다. PEM 형식이어야합니다.

이 명령은 형식에 관계없이 큰 파일을 매우 효과적으로 강력하게 암호화 할 수 있습니다.
알려진 문제 : 대용량 파일 (> 600MB)을 암호화하려고하면 문제가 발생합니다. 오류가 발생하지 않지만 암호화 된 파일이 손상됩니다. 항상 각 파일을 확인하십시오! (또는 PGP 사용-공개 키로 파일 암호화를 더 많이 지원함)

파일 해독 :

openssl smime -decrypt -binary -in encrypted.zip.enc -inform DER -out decrypted.zip -inkey private.key -passin pass:your_password

무엇입니까 :

  • -inform DER- 위의 -outform과 동일
  • -inkey private.key- 개인 키의 파일 이름입니다. 이는 PEM 형식이어야하며 암호로 암호화 할 수 있습니다.
  • -passin pass : your_password- 개인 키 암호화를위한 비밀번호입니다. ( 암호 인수 )

.NET을 사용하여 대용량 파일을 직접 암호화 할 수 없습니다 rsautl. 대신 다음과 같이하십시오.

  1. 를 사용하여 키를 생성합니다 openssl rand.openssl rand 32 -out keyfile
  2. 다음을 사용하여 키 파일 암호화 openssl rsautl
  3. openssl enc1 단계에서 생성 된 키를 사용 하여 를 사용하여 데이터를 암호화합니다 .
  4. 암호화 된 데이터로 암호화 된 키 파일을 패키징하십시오. 수신자는 개인 키로 키를 해독 한 다음 결과 키로 데이터를 해독해야합니다.

-stream 옵션을 사용하여 대용량 파일을 암호화 할 수 있지만 하드웨어 제한으로 인해 결과 파일을 해독 할 수 없기 때문에 smime을 사용하여 매우 큰 파일을 암호화하는 것은 권장되지 않습니다 . 큰 파일 해독 문제를 참조하십시오.

위에서 언급했듯이 공개 키 암호화는 임의로 긴 파일을 암호화하기위한 것이 아닙니다. 따라서 다음 명령은 암호문을 생성하고 대칭 암호화를 사용하여 파일을 암호화 한 다음 비대칭 (공개 키)을 사용하여 암호문을 암호화합니다. 참고 : smime에는 암호 구문을 암호화하기위한 기본 공개 키 및 백업 키 사용이 포함됩니다. 백업 공개 / 개인 키 쌍은 신중할 것입니다.

임의 암호 생성

RANDFILE 값을 현재 사용자가 액세스 할 수있는 파일로 설정하고 passwd.txt 파일을 생성하고 설정을 정리합니다.

export OLD_RANDFILE=$RANDFILE
RANDFILE=~/rand1
openssl rand -base64 2048 > passwd.txt
rm ~/rand1
export RANDFILE=$OLD_RANDFILE

암호화

아래 명령을 사용하여 passwd.txt 내용을 암호로 사용하고 AES256을 base64 (-a 옵션) 파일로 사용하여 파일을 암호화합니다. 기본 공개 키 및 백업 키를 사용하여 비대칭 암호화를 사용하여 passwd.txt를 파일 XXLarge.crypt.pass로 암호화합니다.

openssl enc -aes-256-cbc -a -salt -in XXLarge.data -out XXLarge.crypt -pass file:passwd.txt
openssl smime -encrypt -binary -in passwd.txt -out XXLarge.crypt.pass -aes256 PublicKey1.pem PublicBackupKey.pem
rm passwd.txt

복호화

Decryption simply decrypts the XXLarge.crypt.pass to passwd.tmp, decrypts the XXLarge.crypt to XXLarge2.data, and deletes the passwd.tmp file.

openssl smime -decrypt -binary -in XXLarge.crypt.pass -out passwd.tmp -aes256 -recip PublicKey1.pem -inkey PublicKey1.key
openssl enc -d -aes-256-cbc -a -in XXLarge.crypt -out XXLarge2.data -pass file:passwd.tmp
rm passwd.tmp

This has been tested against >5GB files..

5365295400 Nov 17 10:07 XXLarge.data
7265504220 Nov 17 10:03 XXLarge.crypt
      5673 Nov 17 10:03 XXLarge.crypt.pass
5365295400 Nov 17 10:07 XXLarge2.data

I found the instructions at http://www.czeskis.com/random/openssl-encrypt-file.html useful.

To paraphrase the linked site with filenames from your example:

Generate a symmetric key because you can encrypt large files with it

openssl rand -base64 32 > key.bin

Encrypt the large file using the symmetric key

openssl enc -aes-256-cbc -salt -in myLargeFile.xml \
  -out myLargeFile.xml.enc -pass file:./key.bin

Encrypt the symmetric key so you can safely send it to the other person

openssl rsautl -encrypt -inkey public.pem -pubin -in key.bin -out key.bin.enc

Destroy the un-encrypted symmetric key so nobody finds it

shred -u key.bin

At this point, you send the encrypted symmetric key (key.bin.enc) and the encrypted large file (myLargeFile.xml.enc) to the other person

The other person can then decrypt the symmetric key with their private key using

openssl rsautl -decrypt -inkey private.pem -in key.bin.enc -out key.bin

Now they can use the symmetric key to decrypt the file

openssl enc -d -aes-256-cbc -in myLargeFile.xml.enc \
  -out myLargeFile.xml -pass file:./key.bin

And you're done. The other person has the decrypted file and it was safely sent.


To safely encrypt large files (>600MB) with openssl smime you'll have to split each file into small chunks:

# Splits large file into 500MB pieces
split -b 500M -d -a 4 INPUT_FILE_NAME input.part.

# Encrypts each piece
find -maxdepth 1 -type f -name 'input.part.*' | sort | xargs -I % openssl smime -encrypt -binary -aes-256-cbc -in % -out %.enc -outform DER PUBLIC_PEM_FILE

For the sake of information, here is how to decrypt and put all pieces together:

# Decrypts each piece
find -maxdepth 1 -type f -name 'input.part.*.enc' | sort | xargs -I % openssl smime -decrypt -in % -binary -inform DEM -inkey PRIVATE_PEM_FILE -out %.dec

# Puts all together again
find -maxdepth 1 -type f -name 'input.part.*.dec' | sort | xargs cat > RESTORED_FILE_NAME

Maybe you should check out the accepted answer to this (How to encrypt data in php using Public/Private keys?) question.

Instead of manually working around the message size limitation (or perhaps a trait) of RSA, it shows how to use the S/mime feature of OpenSSL to do the same thing and not needing to juggle with the symmetric key manually.

참고URL : https://stackoverflow.com/questions/7143514/how-to-encrypt-a-large-file-in-openssl-using-public-key

반응형