|
| 1 | +// |
| 2 | +// s_des.swift |
| 3 | +// Houses all the core functionality of the Simplified Data Encryption Standard (DES). |
| 4 | +// |
| 5 | +// Created by Matt Manzi on 2/25/20. |
| 6 | +// Project 2 of CMSC 487, Spring 2020. |
| 7 | +// |
| 8 | + |
| 9 | +import Foundation |
| 10 | + |
| 11 | +let ROUNDS = 4 |
| 12 | +let IP: [[UInt8]] = [ |
| 13 | + [2, 6, 3, 1, 4, 8, 5, 7], |
| 14 | + [4, 1, 3, 5, 7, 2, 8, 6] |
| 15 | +] |
| 16 | + |
| 17 | +/** |
| 18 | + TODO: comment |
| 19 | + */ |
| 20 | +func cipher(_ block: UInt8, using key: UInt16) -> UInt8 { |
| 21 | + |
| 22 | + // initial permutation |
| 23 | + let permuted = permute(block, by: IP[0]) |
| 24 | + |
| 25 | + /* |
| 26 | + split block into L and R, like: |
| 27 | + MSb LSb |
| 28 | + +-----------+-----------+ |
| 29 | + | r | l | |
| 30 | + +-----------+-----------+ |
| 31 | + */ |
| 32 | + var l: UInt8 = (permuted & 0x0F) |
| 33 | + var r: UInt8 = (permuted & 0xF0) >> 4 |
| 34 | + |
| 35 | + // perform cipherment rounds |
| 36 | + for i in 0..<ROUNDS { |
| 37 | + |
| 38 | + let k = ks(i + 1, key) |
| 39 | + |
| 40 | + let temp = l ^ f(r, k) |
| 41 | + l = r |
| 42 | + r = temp |
| 43 | + |
| 44 | + } |
| 45 | + |
| 46 | + /* |
| 47 | + combine L and R into single block, like: |
| 48 | + MSb LSb |
| 49 | + +-----------+-----------+ |
| 50 | + | l | r | |
| 51 | + +-----------+-----------+ |
| 52 | + */ |
| 53 | + let preoutput: UInt8 = (l << 4) + r |
| 54 | + |
| 55 | + // inverse initial permutation |
| 56 | + let output = permute(preoutput, by: IP[1]) |
| 57 | + |
| 58 | + return output |
| 59 | +} |
| 60 | + |
| 61 | +/** |
| 62 | + TODO: comment |
| 63 | + */ |
| 64 | +func permute<T: UnsignedInteger>(_ bits: T, by vector: [T]) -> T { |
| 65 | + |
| 66 | + // isolate each bit and move it to it's permutated position |
| 67 | + var permuted: T = 0 |
| 68 | + for (i, bit) in vector.enumerated() { |
| 69 | + let mask: T = 1 << (bit - 1) |
| 70 | + let shift = (i + 1) - Int(bit) |
| 71 | + permuted += (bits & mask) << shift |
| 72 | + } |
| 73 | + |
| 74 | + return permuted |
| 75 | +} |
| 76 | + |
| 77 | +/** |
| 78 | + TODO: implement |
| 79 | + */ |
| 80 | +func ks(_ round: Int, _ key: UInt16) -> UInt8 { |
| 81 | + |
| 82 | + return 0 |
| 83 | +} |
| 84 | + |
| 85 | +/** |
| 86 | + TODO: implement |
| 87 | + */ |
| 88 | +func f(_ halfBlock: UInt8, _ k: UInt8) -> UInt8 { |
| 89 | + |
| 90 | + return 0 |
| 91 | +} |
0 commit comments