Last active
August 29, 2015 14:13
-
-
Save qwzybug/749c4dbe88437295ea01 to your computer and use it in GitHub Desktop.
noodling with devices & generators in swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env swift | |
import Foundation | |
class Dev { | |
let desc: Int32 | |
var data = NSMutableData(length: 1)! | |
init(_ name: String) { | |
desc = Darwin.open("/dev/\(name)", O_RDONLY) | |
} | |
deinit { | |
Darwin.close(desc) | |
} | |
func read() -> UInt8? { | |
var mPtr = UnsafeMutablePointer<UInt8>(data.bytes) | |
if Darwin.read(desc, mPtr, 1) > 0 { | |
return mPtr.memory | |
} | |
return nil | |
} | |
} | |
let devRandom = Dev("random") | |
let randomBytes = lazy(GeneratorOf(devRandom.read)) | |
for byte in randomBytes { | |
print(String(format: "%02X", byte)) | |
if byte == 0 { | |
println() | |
break | |
} | |
} | |
func unZip2<T,U>(s: [(T, U)]) -> ([T], [U]) { | |
return (s.map{ $0.0 }, s.map{ $0.1 }) | |
} | |
let text = "I am the very model of a modern major general" | |
// XOR is strong digital defense | |
let superSecureCipher = { (m: Byte, k: Byte) -> (Byte, Byte) in (m ^ k, k) } | |
let (encrypted, key) = unZip2(map(Zip2(text.utf8, randomBytes), superSecureCipher)) | |
println("Encrypted: " + "".join(encrypted.map{ String(format: "%02X", $0)})) | |
println("One-time pad: " + "".join(key.map{ String(format: "%02X", $0)})) | |
let decrypted = unZip2(map(Zip2(encrypted, key), superSecureCipher)).0 | |
println("Decrypted: " + "".join(decrypted.map{ String(UnicodeScalar($0)) })) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment