Skip to content

Instantly share code, notes, and snippets.

@SlayterDev
Last active February 2, 2016 21:22
Show Gist options
  • Save SlayterDev/9de619a7a7ce5b9b33d9 to your computer and use it in GitHub Desktop.
Save SlayterDev/9de619a7a7ce5b9b33d9 to your computer and use it in GitHub Desktop.
Simple implementation of the RC4 stream cipher in Swift. Currently only encrypts. Feel free to make it better.
//
// RC4
//
// Created by Bradley Slayter on 2/2/16.
// Copyright © 2016 Bradley Slayter. All rights reserved.
//
import Foundation
struct ByteStream: GeneratorType {
typealias Element = UInt8
var i = 0
var j = 0
var key: [UInt8]
init(key: [UInt8]) {
self.key = key
}
mutating func next() -> Element? {
i = (i + 1) % 256
j = (j + Int(key[i])) % 256
(key[i], key[j]) = (key[j], key[i])
return key[(Int(key[i]) + Int(key[j])) % 256]
}
}
func keyInit(key: [UInt8]) -> [UInt8] {
var K = [UInt8]()
for i in 0..<256 {
K.append(UInt8(i))
}
var j = 0
for i in 0..<256 {
let index = Int(K[i])
j = (j + index + Int(key[i % key.count])) % 256
(K[i], K[j]) = (K[j], K[i])
}
return K
}
func encrypt(text: [UInt8], key: [UInt8]) -> String {
var cipherText = [UInt8]()
var byteStream = ByteStream(key: key)
for ch in text {
let cipherByte = ch ^ byteStream.next()!
cipherText.append(cipherByte)
}
return String(bytes: cipherText, encoding: NSASCIIStringEncoding)!
}
print("Enter a key> ", separator: "", terminator: "")
let key = readLine(stripNewline: true)
print("Enter a message> ", separator: "", terminator: "")
let message = readLine(stripNewline: true)
let keyStream = keyInit(Array(key!.utf8))
let cipherText = encrypt(Array(message!.utf8), key: keyStream)
print("Cipher text: \(cipherText)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment