Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Network Lab. Encryption 컴퓨터 네트워크 실험실 조한진 / 이희규.

Similar presentations


Presentation on theme: "Computer Network Lab. Encryption 컴퓨터 네트워크 실험실 조한진 / 이희규."— Presentation transcript:

1 Computer Network Lab. Encryption 컴퓨터 네트워크 실험실 조한진 / 이희규

2 Computer Network Lab. 2 목 차목 차 n Streams and Blocks n Block Cipher n Algorithms n javax.crypto.Cipher n Cipher’s Close Relatives n Passphrase Encryption n Inside Cipher l BlockCipher l CBCWrapper l CFBWrapper n Hybird System n 결 론

3 Computer Network Lab. 3 Encryption n 암호 l 비밀을 보호하기 위해 사용되는 도구 n 대칭 (symmetric)/ 비밀키 (private key) l 데이터를 암호화 / 복호화하는데 하나의 비밀키 사용 n 비대칭 (asymmetric)/ 공개키 (public key) l 한 쌍의 키 사용 n 하이브리드 (hybrid) l 비대칭 암호는 private key( 비밀키, 세션키 ) 를 교환하기 위해 사용

4 Computer Network Lab. 4 Streams and Blocks n 블록 암호 l 고정된 크기 ( 일반적으로 64 비트 ) 의 데이터 블록으로 암호화 / 복호화 한다. n 스트림 암호 l 비트나 바이트들의 스트림에 작용 l 블록 암호는 적절한 모드 (CFB) 를 사용하여 스트림 암 호처럼 만들어질 수 있다. l 블록 암호는 비대칭 암호이다.

5 Computer Network Lab. 5 Block Ciphers n Padding l 마지막 불완전한 블록을 보정하기 위하여, 패딩 (padding) 이 필요 l 패딩 기법은 평문의 마지막 블록을 암호화되기 전에 데이터로 채우는 것 l 복호화 쪽의 상응하는 절차는 패딩을 제거하고 평문 의 실제 길이를 다시 저장

6 Computer Network Lab. 6 n PKCS#5 는 공개키 암호화 표준 n RSA Data Security, Inc 에 의해 발표 n getPadding() 메소드를 이용해서 Cipher 의 패딩 기 법을 알 수 있다. n SunJCE provider 에서, PKCS#5 패딩에 대한 이름 을 "PKCS5Padding” 으로 정의 PKCS#5

7 Computer Network Lab. 7 PKCS#5 블록 패딩 예제 나머지 평문 평문의 마지막 블록 5 바이트 2 바이트 없음 3 3 3 3 3 3 6 6 6 6 6 6 6 6 6 6 6 6 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8

8 Computer Network Lab. 8 Modes n 암호의 mode 는 평문의 블록이 암호문의 블록으 로 암호화되는 방법을 결정 n getMode() 메소드를 호출함으로써 Cipher 의 모드 를 알아낼 수 있다. n SunJCE provider 는 ECB, CBC, CFB, OFB, PCBC 모드를 지원

9 Computer Network Lab. 9 ECB n ECB(electronic code book) n 평문의 각 블록을 암호문의 블록으로 암호화 n 단점 l 동일한 키를 사용한다면, ECB 모드는 동일한 평문을 항상 동일한 암호문으로 암호화 l 일반적인 인사말, 헤더, 또는 footer( 자료의 각 페이지 하단의 반복 문구 ) l 사용자는 다른 모드를 생각해야 한다.

10 Computer Network Lab. 10 CBC n CBC(Cipher block chaining) n ECB 모드의 단점을 보완 n 평문의 각 블록은 XOR 을 이용하여 이전 블록의 암호문과 조합 l 평문의 첫 번째 블록에 대하여는 암호문으로 IV 사용 l IV 는 일반적으로 랜덤 데이터가 사용 l 데이터를 확실히 복호화하기 위해서 암호문을 동일한 IV 로 초기화

11 Computer Network Lab. 11 CBC 모드 동작 cipher 평문 블록 1 IV 암호문 블록 1 cipher 평문 블록 2 암호문 블록 2 cipher 평문 블록 n 암호문 블록 n 암호문 블록 n-1.... =XOR

12 Computer Network Lab. 12 PCBC n PCBC(Propagating cipher block chaining) n CBC 모드와 유사 n 평문 블록이 암호화 될 때, 이전의 평문 블록과 이전의 암호문 블록으로 XOR n 복호화된 블록도 이전의 평문과 암호문 블록으 로 XOR

13 Computer Network Lab. 13 CFB n CFB(Cipher feedback) n 블록 암호가 스트림 암호처럼 동작 n CBC 처럼 IV 를 이용하지만, 내부 처리가 필요 n 블록 암호는 블록 크기보다 작은 데이터의 조각 을 암호화할 수 있다. l CFB 는 하나의 비트에서부터 블록 크기가지 어떠한 데 이터의 크기도 암호화할 수 있다. l CFB 는 동시에 한 바이트 (8 비트 ) 를 암호화 / 복호화 하 는데 사용 - CFB8

14 Computer Network Lab. 14 동시에 8 비트를 암호화하는 CFB

15 Computer Network Lab. 15 OFB n OFB(Output feedback) n 내부 버퍼가 갱신되는 것을 제외하고 CFB 모드처럼 동작 n 내부 버퍼가 왼쪽으로 이동될 때, 오른쪽의 공간은 암호 화된 버퍼의 가장 왼쪽 비트로 채워진다. n 이론적으로, OFB 는 암호의 블록 크기보다 작거나 같은 어떤 비트 크기와 사용될 수 있다. n 피드백 크기가 기본적 암호의 블록 크기보다 작을 때에는 OFB 는 약하다. n 피드백 크기가 암호 블록 크기와 같을 때 사용

16 Computer Network Lab. 16 Other modes n Bruce Schneier 의 "Applied Cryptography” n 모드는 암호분석가에게 암호의 저항력과 전송 오류로부 터 회복할 수 있는 능력에 대해 영향 n ECB l 암호문의 한 블록에서 전송 오류는 단지 하나의 복호화된 평문 블록에만 영향을 미친다. n CBC l 암호문의 한 블록이 잘못되면 복호화된 평문의 두 블록에 영향을 미친다. n OFB l 하나의 잘못된 비트는 복호화된 평문의 한 비트에만 영향을 미친 다.

17 Computer Network Lab. 17 Algorithms n Security API 에서 프로바이더 구조의 특징 l 프로그램을 다시 작성할 필요 없이 다른 암호화 알고 리즘을 사용할 수 있다. n SunJCE 프로바이더는 세 개의 암호 알고리즘을 포함하고 있다. n 다른 프로바이더들은 다른 알고리즘을 포함하고 있다.

18 Computer Network Lab. 18 암호 알고리즘

19 Computer Network Lab. 19 암호 알고리즘 프로바이더

20 Computer Network Lab. 20 javax.crypto.Cipher(1/4) n javax.crypto.Cipher 는 암호 알고리즘을 캡슐화 n Cipher 는 데이터를 암호화 / 복호화 n Cipher 클래스는 비대칭 ( 공개키 ) 과 대칭 ( 비밀키 ) 알고리 즘을 포함 n 이 클래스는 JCE 의 일부분으로, 미국 밖으로 수출될 수 없는 소프트웨어 중에 하나이다. n Cryptix(http://www.systemics.com/software/cryptix-java/) n IAIK-JCE(http://wwwjce.iaik.tu-graz.ac.at/) n Cipher 는 추상 클래스이다. n JCA 에서의 클래스에서처럼, 가용한 인스턴스를 반환하 는 factory 메소드를 제공한다.

21 Computer Network Lab. 21 javax.crypto.Cipher(2/4) n Cipher 를 이용하여 세 단계로 처리 1. getInstance() factory 를 이용하여 Cipher 를 얻는다. 2. init() 를 이용하여 암호화 / 복호화에 대해 Cipher 를 초기 화한다. 이러한 메소드들은 모드 (Cipher.ENCRYPT_MODE 또는 Cipher.DECRYPT_MODE) 와 Key 를 허용한다. 3. update() 와 doFinal() 메소드를 이용하여 데이터를 암호 화 / 복호화 한다.

22 Computer Network Lab. 22 javax.crypto.Cipher(3/4) n 제 1 장의 SecretWriting 예제 Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] raw = cipher.doFinal(stringBytes);

23 Computer Network Lab. 23 javax.crypto.Cipher(4/4) n getInstance() 메소드의 두 가지 타입 스트링 n 알고리즘 l 알고리즘 이름만 명시할수 있다. l 프로바이더가 알고리즘 구현은 무엇이든지 기본 모드 와 패딩 기법을 제공한다. n 알고리즘 / 모드 / 패딩 l getInstance() 를 호출할 때, 알고리즘 / 모드 / 패딩 기법을 명시할 수 있다.

24 Computer Network Lab. 24 Getting a Cipher(1/2) n public static Cipher getInstance(String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException l factory 메소드는 주어진 알고리즘에 대하여 Cipher 를 반환 l 일반적으로 알고리즘 이름은 패딩 기법과 암호 모드와 같은 추 가 정보를 포함 n public static Cipher getInstance(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException l 이 메소드는 위와 동일하지만, 주어진 알고리즘의 명명된 프로 바이더의 구현을 사용

25 Computer Network Lab. 25 Getting a Cipher(2/2)

26 Computer Network Lab. 26 Basic Information n public final Provider getProvider() n public final init getBlockSize() n public final init getOutputSize(init inputLen) throws IllegalStateException n public final byte[] getIV()

27 Computer Network Lab. 27 Initializing a Cipher(1/3) n public static final int ENCRYPT_MODE n public static final int DECRYPT_MODE n public final void init(int opmode, Key key) throws InvalidKeyException n public final void init(int opmode, Key key, SecureRandom random) throws InvalidKeyException

28 Computer Network Lab. 28 Initializing a Cipher(2/3) n public final void init(int opmode, Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException n public final void init(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException

29 Computer Network Lab. 29 Initializing a Cipher(3/3) //First obtain iv, a byte array, and sessionKey, a DES key. Cipher cipher = Cipher.getInstance(""DES/CBC/PKCS5Padding); IvParameterSpec spec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, sessionKey, spec);

30 Computer Network Lab. 30 Feeding Data to a Cipher(1/7) n public final byte[] update(byte[] input) throws IllegalStateException n public final byte[] update(byte[] input, int inputOffset, int inputLen) throws IllegalStateException n public final int update(byte[] input, int inputOffset, int inputLen, byte[] output) throws IllegalStateException, ShortBufferException n public final int update(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws IllegalStateException, ShortBufferException

31 Computer Network Lab. 31 Feeding Data to a Cipher(2/7) Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] plain5 = "comic".getBytes(); byte[] plain7 = "serious".getBytes(); byte[] step1 = cipher.update(Plain5); byte[] step2 = cipher.update(Plain7);

32 Computer Network Lab. 32 Feeding Data to a Cipher(3/7) Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] plain5 = "comic".getBytes(); byte[] plain7 = "serious".getBytes(); int outputLength = cipher.getOutputSize(plain5.length + plain7.length); byte[] ciphertext = new byte[outputLength]; int length1= cipher.update(plain5, 0, plain5.length, ciphertext); int length2= cipher.update(plain7, 0, plain7.length, ciphertext, length1);

33 Computer Network Lab. 33 Feeding Data to a Cipher(4/7) n public final byte[] doFinal() throws IllegalStateException, IllegalBlockSizeException,BadPaddingException n public final init doFinal(byte[] output, int outputOffset) throws IllegalStateException, IllegalBlockSizeException, ShortBufferException, BadPaddingException n public final byte[] doFinal(byte[] input) throws IllegalStateException,IllegalBlockSizeException, BadPaddingException

34 Computer Network Lab. 34 Feeding Data to a Cipher(5/7) n public final byte[] doFinal(byte[] input, int inputOffset, int inputLen) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException n public final int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output) throws IllegalStateException, IllegalBlockSizeException, ShortBufferException, BadPaddingException n public final int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws IllegalStateException, IllegalBlockSizeException, ShortBufferException, BadPaddingException

35 Computer Network Lab. 35 Feeding Data to a Cipher(6/7) Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] plain5 = "comic".getBytes(); byte[] plain7 = "serious".getBytes(); int outputLength = cipher.getOutputSize(plain5.length + plain7.length); byte[] ciphertext = new byte[outputLength]; int length1= cipher.update(Plain5, 0, plain5.length, ciphertext); int length2= cipher.update(Plain7, 0, plain7.length, ciphertext, length1); int length3= cipher.doFinal(ciphertext, length1 + length2);

36 Computer Network Lab. 36 Feeding Data to a Cipher(7/7) Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] plaintext = "comicserious".getBytes(); byte[] ciphertext = cipher.doFinal(plaintext);

37 Computer Network Lab. 37 Cipher’s Close Relatives(1/9) n Cipher Streams l javax.crypto.CipherInputStream l javax.crypto.CipherOutputStream

38 Computer Network Lab. 38 Cipher’s Close Relatives(2/9) - Cloak - import java.security.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; import javax.crypto.Cipher; import java.io.*; public class Cloak { public static final int kBufferSize = 8192; public static void main(String[] args) throws Exception {

39 Computer Network Lab. 39 Cipher’s Close Relatives(3/9) //Check arguments. if (args.length < 3) { System.out.println("Usage: Cloak -e|-d inputfile outputfile"); return; } Key key; try { ObjectInputStream in = new ObjectInputStream(new FileInputStream("SecretKey.ser")); key = (Key)in.readObject(); in.close(); }

40 Computer Network Lab. 40 Cipher’s Close Relatives(4/9) catch (Exception e) { KeyGenerator generator = KeyGenerator.getInstance("DES"); generator.init(new SecureRandom()); key = generator.generateKey(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("SecretKey.ser")); out.writeObject(key); out.close(); } // Get a cipher object. Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

41 Computer Network Lab. 41 Cipher’s Close Relatives(5/9) if(args[0].indexOf("e") != -1) cipher.init(Cipher.ENCRYPT_MODE, key); else cipher.init(Cipher.DECRYPT_MODE, key); FileInputStream in = new FileInputStream(args[1]); FileOutputStream fileOut = new FileOutputStream(args[2]); CipherOutputStream out = new CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize];

42 Computer Network Lab. 42 Cipher’s Close Relatives(6/9) int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); }

43 Computer Network Lab. 43 Cipher’s Close Relatives(7/9) n Javax.crypto.SealedObject public SealedObject(Serializable object, Cipher c) throws IOExecption, IllegalBlockSizeException public final Object getObject(Cipher c) throws IOException, ClassNotFoundException, IllegalBlockSizeException, BadPaddingException

44 Computer Network Lab. 44 Cipher’s Close Relatives(8/9) // set up the socket connection ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); out.writeObject(secretObject); - Sealed Version- // set up the socket connection and obtain the key ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); SealedObject so = new SealedObject(secretObject, cipher); out.WriteObject(so);

45 Computer Network Lab. 45 Cipher’s Close Relatives(9/9) // set up the socket connection and obtain the key ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); SealedObject so = (SealedObject)in.readObject(); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key); Object secretObject = so.getObject(cipher);

46 Computer Network Lab. 46 Passphrase Encryption(1/9) n Salt and Vinegar md5( gandalf ) md5( sex ) md5( secret )

47 Computer Network Lab. 47 Passphrase Encryption(2/9) - salt - md5(0, gandalf ) md5(0, sex ) md5(0, secret ) md5(1, gandalf ) md5(1, sex ) md5(1, secret ) md5(2, gandalf ) md5(2, sex ) md5(2, secret ) md5(3, gandalf ) md5(3, sex ) md5(3, secret )

48 Computer Network Lab. 48 Passphrase Encryption(3/9) - iteration - md5( gandalf ) md5( sex ) md5( secret ) md5(md5( gandalf )) md5(md5( sex )) md5(md5( secret )) md5(md5(md5( gandalf ))) md5(md5(md5( sex ))) md5(md5(md5( secret )))

49 Computer Network Lab. 49 Passphrase Encryption(4/9) - PBE - import java.io.*; import java.security.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; public class PBE public static void main(String[] args) throws Exception { String options = args[0]; String passphrase = args[1]; File inputFile = new File(args[2]); File outputFile = new File(args[3]);

50 Computer Network Lab. 50 Passphrase Encryption(5/9) String algorithm = "PBEWithMD5AndDES"; byte[] salt = new byte[8]; int iterations = 20; boolean encrypting = (options.indexOf("e") != -1); //Create a key from the supplied passphrase. KeySpec ks = new PBEKeySpec(passphrase); SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm); SecretKey key = skf.generateSecret(ks);

51 Computer Network Lab. 51 Passphrase Encryption(6/9) //Read the input FileInputStream in = new FileInputStream(inputFile); int length = (int)inputFile.length(); if (!encrypting) in.read(salt); byte[] input = new byte[length - (encrypting ? 0 : 8)]; in.read(input); in.close();

52 Computer Network Lab. 52 Passphrase Encryption(7/9) if (encrypting) { //Create the salt from eight bytes of the digest of P || M. MessageDigest md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes()); md.update(input); byte[] digest = md.digest(); System.arraycopy(digest, 0, salt, 0, 8); } //Create the algorithm parameters. AlgorithmParameterSpec aps = new PBEParameterSpec(salt, iterations);

53 Computer Network Lab. 53 Passphrase Encryption(8/9) //Encrypt or decrypt the input. Cipher cipher = Cipher.getInstance(algorithm); int mode = encrypting ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE; cipher.init(mode, key, aps); byte[] output = cipher.doFinal(input); //Write the output OutputStream out = new FileOutputStream(outputFile); if (encrypting) out.write(salt); out.write(output); out.close(); }}

54 Computer Network Lab. 54 Passphrase Encryption(9/9) c:\type plaintext Meet me at midnight down by the old rail yard. c:\java PBE -e "This is the passphrase." plaintexst ciphertext c:\type ciphertext "_>9_'>y++- 8_PH[ +o+>p&->>p 'v > _w31_u_y. '<O+,_+__F_TA=3a+f|+ c:java PBE -d "This is the passphrase." plaintexst ciphertext c:type decryped Meet me at midnight down by the old rail yard. c:\

55 Computer Network Lab. 55 Inside Cipher(1/4) n SPI l Setup  protected abstract void engineSetMode(String mode) throws NoSuchAlgorithmException  protected abstract void engineSetPadding(String padding) throws NoSuchPaddingException l Basic information  protected abstract int engineGetBlockSize()  protected abstract int engineGetOutputSize(int inputLen)  protected abstract byte[] engineGetIV()

56 Computer Network Lab. 56 Inside Cipher(2/4) Initializing  protected abstract void engineInit(int opmode, Key key, SecureRandom random) throws InvalidKeyException  protected abstract void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException

57 Computer Network Lab. 57 Inside Cipher(3/4) Feeding  protected abstract byte[] engineUpdate(byte[] input, int inputOffset, int inputLen)  protected abstract int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)  protected abstract byte[] engineDoFinal(byte[] input,int inputOffset,int inputLen)  protected abstract int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)

58 Computer Network Lab. 58 Inside Cipher(4/4) l BlockCipher  protecetd abstract int engineTransformBlock(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws ShortBufferException  protecetd abstract int engineTransformBlockFinal(byte[] input,int inputOffset, int inputLength, byte[] output, int outputOffset) throws ShortBufferException

59 Computer Network Lab. 59 BlockCipher(1/10) - BlockCipher - package oreilly.jonathan.crypto; import java.math.BigInteger; import java.security.*; import java.security.spec.*; import javax.crypto.*; public abstract class BlockCipher extends CipherSpi { protected abstract int engineTransformBlock(byte[] input, int inputOffset, int inputLengh, byte[] output, int outputOffset) throws ShortBufferException; protected abstract int engineTransformBlockFinal(byte[] input, int inputOffset, int inputLengh, byte[] output, int outputOffset) throws ShortBufferException;

60 Computer Network Lab. 60 BlockCipher(2/10) protected byte[] mBufferedData; protected int mBufferedLength; protected void checkBufferedData() { if (mBufferedData == null || mBufferedData.length != engineGetBlockSize()) { mBufferedData = new byte[engineGetBlockSize()]; mBufferedLength = 0; } } protected int getBufferedDataLength () { checkBufferedData(); return mBufferedLength; }

61 Computer Network Lab. 61 BlockCipher(3/10) protected void getBufferedData(byte[] output, int offset) { checkBufferedData(); System.arraycopy(mBufferedData, 0, output, offset, mBufferedLength); mBufferedLength = 0; } protected void addToBufferedData(byte[] input, int offset, int length) { checkBufferedData(); System.arraycopy(input, offset, mBufferedData, mBufferedLength, length); return mBufferedLength += length; }

62 Computer Network Lab. 62 BlockCipher(4/10) // 단순히 두번째 오버로드된 메소드 호출 protected void engineUpdate(byte[] input, int inputOffset, int inputLen) { int length = 0; byte[] out = new byte[engineGetOutputSize(inputLen)]; try { length = engineUpdate(input, inputOffset, inputLen, out, 0); } catch (ShortBufferException sbe) {} if (length < out.length) { byte[] shorter = new byte[length]; System.arraycopy(out, 0, shorter, 0, length); out = shorter; } return out;}

63 Computer Network Lab. 63 BlockCipher(5/10) protected int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException { // Create a single array of input data.(input + buffer) int bufferedLength = getBufferedDataLength(); byte[] totalInput = new byte[inputLen + bufferedLength]; getBufferedData(totalInput, 0); if (inputLen > 0) System.arraycopy(input, inputOffset, totalInput, bufferedLength, inputLen);

64 Computer Network Lab. 64 BlockCipher(6/10) // 마지막 블록의 위치를 계산한다.. int blockSize = engineGetBlockSize(); int lastblockSize = totalInput.length % blockSize; int lastblockOffset = totalInput.length - lastblockSize; // 마지막 블록을 남겨 놓고 암호화. int outputLength = 0; for (int i = 0; i < lastblockOffset; i += blockSize) outputLength += engineTransformBlock(totalInput, i, blickSize, output, outputOffset + outputLength); // Copy the remainder into mBufferedData. addToBufferedData(totalInput, lastblockOffset, lastblockSize); return outputLength; } // 출력의 크기를 리턴

65 Computer Network Lab. 65 BlockCipher(7/10) // 두번째 오버로드된 버전을 호출 protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { int length = 0; byte[] out = new byte[engineGetOutputSize(inputLen)]; try { length = engineDoFinal(input, inputOffset, inputLen, out, 0); } catch (ShortBufferException sbe) {} if (length < out.length) { byte[] shorter = new byte[length]; System.arraycopy(out, 0, shorter, 0, length); out = shorter; } return out; }

66 Computer Network Lab. 66 BlockCipher(8/10) protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws IllegalBlockSizeException, IllegalBlockSizeException, BadPaddingException { // 입력 데이터의 하나의 배열 생성 int bufferedLength = getBufferedDataLength(); byte[] totalInput = new byte[inputLen + bufferedLength]; getbufferedData(totalInput, 0); if (inputLen > 0) System.arraycopy(input, inputOffset, totalInputm bufferedLength, inputLen);

67 Computer Network Lab. 67 BlockCipher(9/10) // 단편 블록이나 전체 블록의 위치를 찾는다. int blockSize = engineGetBlockSize(); int lastBlockSize = totalInput.length % blockSize; if (lastBlockSize == 0 && totalInput.length > 0) lastBlockSize = blockSize; int lastBlockOffset = totalInput.length - lastBlockSize; // 마지막 블록을 남겨놓고 암호화 처리 int outputLength = 0; for (int i = 0; i < lastBlockOffset; i += blockSize) outputlength += engineTransformBlock(totalInput, i, blockSize, output, outputOffset + outputLength);

68 Computer Network Lab. 68 BlockCipher(10/10) // Transform the final partial or full block. outputLength += engineTransformBlockFinal(totalInput, lastBlockOffset, lastBlockSize, output, outputOffset + outputLength); return outputLength; }

69 Computer Network Lab. 69 CBCWrapper(1/14) - CBCWrapper - package oreilly.jonathan.crypto; import java.security.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; public class CBCWrapper extends BlockCipher {

70 Computer Network Lab. 70 CBCWrapper(2/14) protected int mState; protected Cipher mWrappedCipher; protected byte[] mBuffer; public CBCWrapper() throws NoSuchAlgorithmException, NoSuchPaddingException { // Default to DES. this(Cipher.gerInstance("DES/ECB/NoPadding")); } protected CBCWrapper(Cipher wrapped) { mWrappedCipher = wrapped };

71 Computer Network Lab. 71 CBCWrapper(3/14) // CBC 모드와 PKCS5Padding 만을 사용 protected void engineSetMode(String mode) throws NoSuchAlgorithmException { throw new NoSuchAlgorithmException ("CBCWrapper suppors no modes."); } protected void engineSetPadding(String Padding) throws NoSuchPaddingException { throw new NoSuchPaddingException ("CBCWrapper suppors no Padding."); }

72 Computer Network Lab. 72 CBCWrapper(4/14) protected int engineGetBlockSize() { return mWrappedCipher.getBlockSize(); } // 입력 데이터의 크기에 대해 출력 데이터 리턴 protected int engineGetOutputSize(int inLen) { int blockSize = mWrappedCipher.getBlockSize(); int length = inLen + getBufferedDataLength(); int blocks = (length + blockSize - 1) / blockSize; if (mState == Cipher.ENCRYPT_MODE && length % blockSize == 0) blocks++; return blockSize * blocks; }

73 Computer Network Lab. 73 CBCWrapper(5/14) protected byte[] engineGetIV() { return (byte[]) (mbuffer.clone()); } // 두번째 오버로드된 버전을 호출 protected void engineInit(int opmode, key key, SecureRandom random) throws InvalidKeyException { try { engineInit(opmode, key, null, random); } catch (InvalidAlgorithmParameterException iape) {} mBuffer = new byte[mWrappedCipher.getBlockSize() ]; // IV random.nextBytes(mBuffer); }

74 Computer Network Lab. 74 CBCWrapper(6/14) protected void engineInit(int, opmode, key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { mStare = opmode; mWrappedCipher.init(opmode, key, random); if (params != null) { if (params instanceof IvParameterSpec) { IvParameterSpec spec = (IvParameterSpec)params; mBuffer = byte[spec.getIV().clone()); } else throw new InvalidAlgorithmParameterException(); }

75 Computer Network Lab. 75 CBCWrapper(7/14) protected int engineTransformBlock(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws ShortBufferException { if (mState == Cipher.ENCRYPT_MODE) rerurn encryptBlock(input, inputOffset, inputLength, output, outputOffset); else if (mState == Cipher.DECRYPT_MODE) rerurn decryptBlock(input, inputOffset, inputLength, output, outputOffset); return 0; }

76 Computer Network Lab. 76 CBCWrapper(8/14) protected int engineTransformBlockFinal(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws ShortBufferException { int blockSize = mWrappedCipher.getBlockSize() ; if (mState == Cipher.ENCRYPT_MODE) { if (inputLength == blockSize) { int length = encryptBlock(input, inputOffset, inputLength, output, outputOffset); byte[] paddingBlock = pad(null, 0, 0); // 패팅 처리 블록 암호화 length += encryptBlock(paddingBlock, 0, blockSize, output, outputOffset + length); return length; }

77 Computer Network Lab. 77 CBCWrapper(9/14) byte[] paddingBlock; paddingBlock = pad(input, inputOffset, inputLength); return encryptBlock(paddeBlock, 0, blockSize, output, outputOffset); } // 패팅 제거 else if (mState == Cipher.DECRYPT_MODE) { int length = decryptBlock(input, inputOffset, inputLength, output, outputOffset); int paddingLength = (int)output[outputOffset + length - 1]; rerurn length - paddingLength; } return 0; }

78 Computer Network Lab. 78 CBCWrapper(10/14) protected byte[] pad(byte[] in, int inOff, int inLen) { int blockSize = mWrappedCipher.getBlockSize() ; byte[] paddedBlock = new byte[blockSize]; if (in != null) System.arraycopy(in, inOff, paddedBlock, 0, inLen); for (int i = inLen; i < blockSize; i++) paddedBlock[i] = (byte) (blockSize - inLen); return paddedBlock; }

79 Computer Network Lab. 79 CBCWrapper(11/14) protected int encryptBlock(byte[] in, int inOff, int inLen, byte[] out, int outOff) { // XOR plaintext with mBuffer int blockSize = mWrappedCipher.getBlockSize() ; byte[] amalgam = new byte[blockSize]; for (int i = 0; i < blockSize; i++) amalgam[i] = (byte) (in[inOff + i] ^ mBuffer[i]);

80 Computer Network Lab. 80 CBCWrapper(12/14) // encrypt block byte[] Ciphertext = null; try { ciphertext = mWrappedCipher.doFinal(amalgam); } catch (IllegalBlockSizeException ibse) {} catch (BadPaddingException bpe) {} // ciphertext 를 out 과 mBuffer System.arraycopy(ciphertext, 0, out, outOff, blockSize); System.arraycopy(ciphertext, 0, mBuffer, 0, blockSize); rerurn blockSize; }

81 Computer Network Lab. 81 CBCWrapper(13/14) protected int decryptBlock(byte[] in, int inOff, int inLen, byte[] out, int outOff) { // decrypt block int blockSize = mWrappedCipher.getBlockSize() ; byte[] ciphertext = new byte[blockSize]; System.arraycopy(in, inOff, ciphertext, 0, blockSize); byte[] amalgam = null; try { amalgam = mWrappedCipher.doFinal(ciphertext); } catch (IllegalBlockSizeException ibse) {} catch (BadPaddingException bpe) {}

82 Computer Network Lab. 82 CBCWrapper(14/14) // XOR amalgam with mBuffer for (int i = 0; i < blockSize; i++) out[outOff + i] = (byte) (amalgam[i] ^ mBuffer[i]); // put ciphertext in mBuffer System.arraycopy(ciphertext, 0, mBuffer, 0, blockSize); rerurn blockSize; }

83 Computer Network Lab. 83 CFBWrapper(1/11) - CFBWrapper - package oreilly.jonathan.crypto; import java.security.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; public class CFBWrapper extends CipherSpi {

84 Computer Network Lab. 84 CFBWrapper(2/11) protected int mState; //ENCRYPT_MODE, DECRYPT_MODE protected Cipher mWrappedCipher; protected byte[] mBuffer; public class CFBWrapper() // PADDING NO! throws NoSuchAlgorithmException, NoSuchpaddingException { // Default to DES. this(Cipher.getInstance("DES/ECB/NoPadding")); } protected CFBWrapper(Cipher wrapped){ mWrapperCipher = wrapped; }

85 Computer Network Lab. 85 CFBWrapper(3/11) protected void engineSetMode(String mode) throws NoSuchAlgorithmException { throw new NoSuchAlgorithmException("CFBWrapper supports no mode."); } protected void engineSetPadding(String Padding) throws NoSuchPaddingException { throw new NoSuchPaddingException("CFBWrapper supports no Padding."); }

86 Computer Network Lab. 86 CFBWrapper(4/11) protected int engineGetBlockSize(int inLen) { return 1; } protected int engineGetOutputSize(int inLen) { return inLen; } protected byte[] engineGetIV() { return (byte[]) (mBuffer.clone()); } // 두번째 오버로드된 버전을 호출 protected void engineInit(int opmode, key key, SecureRandom random) throws InvalidKeyException { try { engineInit(opmode, key, null, random); } catch (InvalidAlgorithmParameterException iape) {} mBuffer = new byte[mWrappedCipher.getBlockSize() ]; random.nextBytes(mBuffer); }

87 Computer Network Lab. 87 CFBWrapper(5/11) protected void engineInit(int opmode, key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { mState = opmode; mWrappedCipher.init(Cipher.ENCRYPT_MODE, key); if (params != null) { if (params instanceof IvParameterSpec) { IvParameterSpec spec = (IvParameterSpec)params; mBuffer = (byte[]) (spec.getIV().clone()); } else throw new InvalidAlgorithmParameterException(); }

88 Computer Network Lab. 88 CFBWrapper(6/11) // 두번째 오버로드된 버전을 호출 protected byte[] engineUpdate(byte[] input, int intputOffset, int inputLen) { byte[] out = new byte[inptLen]; try engineUpdate(input, inputOffset, inputLen, out, 0); } catch (ShortBufferException sbe) {} rerurn out; } protected int engineUpdate(byte[] input, int intputOffset, int inputLen) byte[] output, int outputOffset) throws ShoftBufferException { int length = o; try length = engineDoFinal(input, inputOffset, inputLen, output, outputOffset); } catch (IllegalBlockSizeException ibse) {} catch (BadPaddingException bpe) {} rerurn length; }

89 Computer Network Lab. 89 CFBWrapper(7/11) // 두번째 오버로드된 버전을 호출 protected byte[] engineDoFinal(byte[] input, int intputOffset, int inputLen) throws IllegalBlockSizeException BadPaddingException { byte[] out = new byte[inptLen]; try { engineDoFinal(input, inputOffset, inputLen, out, 0); } catch (ShortBufferException sbe) {} rerurn out; }

90 Computer Network Lab. 90 CFBWrapper(8/11) protected int engineDoFinal(byte[] input, int intputOffset, int inputLen, byte[] output, int outputOffser) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { for (int i = 0; i < inputLen; i++) { if (mstate== Cipher.ENCRYPT_MODE) output[outoutOffset + i] = encryptByte(input[inputOffset + i]) ; else output[outoutOffset + i] = decryptByte(input[inputOffset + i]) ; } rerurn inputLen; }

91 Computer Network Lab. 91 CFBWrapper(9/11) protected byte encryptByte(byte p) { int blockSize = mWrappedCipher.getBlockSize(); byte[] encryptedBlock = null; try { encryptedBlock = mWrappedCipher.doFinal(mBuffer); } catch (IllegalBlockSizeException ibse) {} catch (BadPaddingException bpe) {} byte left = encryptedblock[0]; //leftmost byte byte c = (byte) (p ^ left); // leftmost XOR plentext shiftBuffer(c); // 1 byte shift return c; }

92 Computer Network Lab. 92 CFBWrapper(10/11) protected byte decryptByte(byte c) { byte[] encryptedBlock = null; try { encryptedBlock = mWrappedCipher.doFinal(mBuffer); } catch (IllegalBlockSizeException ibse) {} catch (BadPaddingException bpe) {} byte left = encryptedblock[0]; byte p = (byte) (c ^ left); shiftBuffer(c); return p; }

93 Computer Network Lab. 93 CFBWrapper(11/11) protected void ShiftBuffer(byte fill) { for (int i = 0; i < mBuffer.length - 1; i++; mBuffer[i] = mBuffer[i + 1] ; mBuffer[mBuffer.length - 1] = fill; }

94 Computer Network Lab. 94 Hybird Systems n PGP n S/MIME n SSL n SET

95 Computer Network Lab. 95 결 론결 론 n Oreilly Package ? n SunJCE & Cryptix JCE 1.2(www.cryptix.org) ?

96 Computer Network Lab. 96 Oreilly Package(1/2) n BlockCipher n CBCWrapper n CFBWrapper n CipherMail n Cloak n Composer n ElGamalCipher n IDEACBCPKCS5 n Message n PBE n POP3

97 Computer Network Lab. 97 Oreilly Package(2/2) n Receiver n SafeTalk n SecretWriting n Session n SessionServer n Skip n SkipClient n Skipper n SkipServer n SMTP


Download ppt "Computer Network Lab. Encryption 컴퓨터 네트워크 실험실 조한진 / 이희규."

Similar presentations


Ads by Google