0001    //
0002    //  Crypto.swift
0003    //  Vapor
0004    //
0005    //  Created by Tanner Nelson on 2/23/16.
0006    //  Copyright © 2016 Tanner Nelson. All rights reserved.
0007    //
0008    
0009    import Foundation
0010    
0011    
0012    #if os(Linux)
0013        import Glibc
0014    #else
0015        import Darwin
0016    #endif
0017    
0018    //
0019    //  SHA2.swift
0020    //  CryptoSwift
0021    //
0022    //  Created by Marcin Krzyzanowski on 24/08/14.
0023    //  Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
0024    //
0025    
0026    
0027    //TODO: func anyGenerator is renamed to AnyGenerator in Swift 2.2, until then it's just dirty hack for linux (because swift >= 2.2 is available for Linux)
0028    private func CS_AnyGenerator
CryptoSwift.swift:44
        return CS_AnyGenerator {
<Element>(body: () -> Element?) -> AnyGenerator<Element> { 0029 #if os(Linux) 0030 return AnyGenerator(body: body) 0031 #else 0032 return AnyGenerator(body: body) 0033 #endif 0034 } 0035 0036 struct BytesSequence
CryptoSwift.swift:118
        for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
: SequenceType { 0037 let chunkSize
CryptoSwift.swift:45
            let end = min(self.chunkSize, self.data.count - offset)
: Int 0038 let data
CryptoSwift.swift:45
            let end = min(self.chunkSize, self.data.count - offset)
CryptoSwift.swift:46
            let result = self.data[offset..<offset + end]
: [UInt8] 0039 0040 func generate() -> AnyGenerator<ArraySlice<UInt8>> { 0041 0042 var offset:Int = 0 0043 0044 return CS_AnyGenerator { 0045 let end = min(self.chunkSize, self.data.count - offset) 0046 let result = self.data[offset..<offset + end] 0047 offset += result.count 0048 return result.count > 0 ? result : nil 0049 } 0050 } 0051 } 0052 0053 class SHA2
CryptoSwift.swift:402
        let sha = SHA2()
{ 0054 init
CryptoSwift.swift:402
        let sha = SHA2()
() { 0055 0056 } 0057 0058 func prepare
CryptoSwift.swift:105
        var tmpMessage = self.prepare(64)
(len:Int) -> Array<UInt8> { 0059 var tmpMessage = message 0060 0061 // Step 1. Append Padding Bits 0062 tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message 0063 0064 // append "0" bit until message length in bits ≡ 448 (mod 512) 0065 var msgLength = tmpMessage.count 0066 var counter = 0 0067 0068 while msgLength % len != (len - 8) { 0069 counter += 1 0070 msgLength += 1 0071 } 0072 0073 tmpMessage += Array<UInt8>(count: counter, repeatedValue: 0) 0074 return tmpMessage 0075 } 0076 0077 var size = 256 0078 0079 var message
CryptoSwift.swift:59
        var tmpMessage = message
CryptoSwift.swift:114
        tmpMessage += (message.count * 8).bytes(64 / 8)
CryptoSwift.swift:403
        sha.message = bytes
: [UInt8] = [] 0080 0081 private var h
CryptoSwift.swift:109
        self.h.forEach {(h) -> () in
:[UInt64] { 0082 return [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19] 0083 } 0084 0085 private var k
CryptoSwift.swift:121
            var M:[UInt32] = [UInt32](count: self.k.count, repeatedValue: 0)
CryptoSwift.swift:148
            for j in 0..<self.k.count {
CryptoSwift.swift:154
                let t1 = H &+ s1 &+ ch &+ UInt32(self.k[j]) &+ M[j]
:[UInt64] { 0086 return [ 0087 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0088 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0089 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0090 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0091 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0092 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0093 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0094 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 0095 ] 0096 } 0097 0098 private func resultingArray
CryptoSwift.swift:180
        self.resultingArray(hh).forEach {
<T>(hh:[T]) -> ArraySlice<T> { 0099 return ArraySlice(hh) 0100 } 0101 0102 0103 //FIXME: I can't do Generic func out of calculate32 and calculate64 (UInt32 vs UInt64), but if you can - please do pull request. 0104 func calculate32
CryptoSwift.swift:404
        return sha.calculate32()
() -> [UInt8] { 0105 var tmpMessage = self.prepare(64) 0106 0107 // hash values 0108 var hh = [UInt32]() 0109 self.h.forEach {(h) -> () in 0110 hh.append(UInt32(h)) 0111 } 0112 0113 // append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits. 0114 tmpMessage += (message.count * 8).bytes(64 / 8) 0115 0116 // Process the message in successive 512-bit chunks: 0117 let chunkSizeBytes = 512 / 8 // 64 0118 for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) { 0119 // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian 0120 // Extend the sixteen 32-bit words into sixty-four 32-bit words: 0121 var M:[UInt32] = [UInt32](count: self.k.count, repeatedValue: 0) 0122 for x in 0..<M.count { 0123 switch (x) { 0124 case 0...15: 0125 let start = chunk.startIndex + (x * sizeofValue(M[x])) 0126 let end = start + sizeofValue(M[x]) 0127 let le = toUInt32Array(chunk[start..<end])[0] 0128 M[x] = le.bigEndian 0129 break 0130 default: 0131 let s0 = rotateRight(M[x-15], n: 7) ^ rotateRight(M[x-15], n: 18) ^ (M[x-15] >> 3) //FIXME: n 0132 let s1 = rotateRight(M[x-2], n: 17) ^ rotateRight(M[x-2], n: 19) ^ (M[x-2] >> 10) 0133 M[x] = M[x-16] &+ s0 &+ M[x-7] &+ s1 0134 break 0135 } 0136 } 0137 0138 var A = hh[0] 0139 var B = hh[1] 0140 var C = hh[2] 0141 var D = hh[3] 0142 var E = hh[4] 0143 var F = hh[5] 0144 var G = hh[6] 0145 var H = hh[7] 0146 0147 // Main loop 0148 for j in 0..<self.k.count { 0149 let s0 = rotateRight(A,n: 2) ^ rotateRight(A,n: 13) ^ rotateRight(A,n: 22) 0150 let maj = (A & B) ^ (A & C) ^ (B & C) 0151 let t2 = s0 &+ maj 0152 let s1 = rotateRight(E,n: 6) ^ rotateRight(E,n: 11) ^ rotateRight(E,n: 25) 0153 let ch = (E & F) ^ ((~E) & G) 0154 let t1 = H &+ s1 &+ ch &+ UInt32(self.k[j]) &+ M[j] 0155 0156 H = G 0157 G = F 0158 F = E 0159 E = D &+ t1 0160 D = C 0161 C = B 0162 B = A 0163 A = t1 &+ t2 0164 } 0165 0166 hh[0] = (hh[0] &+ A) 0167 hh[1] = (hh[1] &+ B) 0168 hh[2] = (hh[2] &+ C) 0169 hh[3] = (hh[3] &+ D) 0170 hh[4] = (hh[4] &+ E) 0171 hh[5] = (hh[5] &+ F) 0172 hh[6] = (hh[6] &+ G) 0173 hh[7] = (hh[7] &+ H) 0174 } 0175 0176 // Produce the final hash value (big-endian) as a 160 bit number: 0177 var result = [UInt8]() 0178 result.reserveCapacity(hh.count / 4) 0179 0180 self.resultingArray(hh).forEach { 0181 let item = $0.bigEndian 0182 result += [UInt8(item & 0xff)] 0183 result += [UInt8((item >> 8) & 0xff)] 0184 result += [UInt8((item >> 16) & 0xff)] 0185 result += [UInt8((item >> 24) & 0xff)] 0186 } 0187 return result 0188 } 0189 0190 } 0191 0192 0193 0194 0195 /* array of bytes */ 0196 extension Int { 0197 /** Array of bytes with optional padding (little-endian) */ 0198 func bytes
CryptoSwift.swift:114
        tmpMessage += (message.count * 8).bytes(64 / 8)
(totalBytes: Int = sizeof(Int)) -> [UInt8] { 0199 return arrayOfBytes(self, length: totalBytes) 0200 } 0201 0202 static func withBytes(bytes: ArraySlice<UInt8>) -> Int { 0203 return Int.withBytes(Array(bytes)) 0204 } 0205 0206 /** Int with array bytes (little-endian) */ 0207 static func withBytes
CryptoSwift.swift:203
        return Int.withBytes(Array(bytes))
(bytes: [UInt8]) -> Int { 0208 return integerWithBytes(bytes) 0209 } 0210 } 0211 0212 0213 0214 0215 0216 // 0217 // HMAC.swift 0218 // CryptoSwift 0219 // 0220 // Created by Marcin Krzyzanowski on 13/01/15. 0221 // Copyright (c) 2015 Marcin Krzyzanowski. All rights reserved. 0222 // 0223 0224 0225 func toUInt32Array
CryptoSwift.swift:127
                    let le = toUInt32Array(chunk[start..<end])[0]
(slice: ArraySlice<UInt8>) -> Array<UInt32> { 0226 var result = Array<UInt32>() 0227 result.reserveCapacity(16) 0228 0229 for idx in slice.startIndex.stride(to: slice.endIndex, by: sizeof(UInt32)) { 0230 let val1:UInt32 = (UInt32(slice[idx.advancedBy(3)]) << 24) 0231 let val2:UInt32 = (UInt32(slice[idx.advancedBy(2)]) << 16) 0232 let val3:UInt32 = (UInt32(slice[idx.advancedBy(1)]) << 8) 0233 let val4:UInt32 = UInt32(slice[idx]) 0234 let val:UInt32 = val1 | val2 | val3 | val4 0235 result.append(val) 0236 } 0237 return result 0238 } 0239 0240 0241 0242 0243 func rotateLeft(v:UInt8, _ n:UInt8) -> UInt8 { 0244 return ((v << n) & 0xFF) | (v >> (8 - n)) 0245 } 0246 0247 func rotateLeft(v:UInt16, _ n:UInt16) -> UInt16 { 0248 return ((v << n) & 0xFFFF) | (v >> (16 - n)) 0249 } 0250 0251 func rotateLeft(v:UInt32, _ n:UInt32) -> UInt32 { 0252 return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n)) 0253 } 0254 0255 func rotateLeft(x:UInt64, _ n:UInt64) -> UInt64 { 0256 return (x << n) | (x >> (64 - n)) 0257 } 0258 0259 func rotateRight(x:UInt16, n:UInt16) -> UInt16 { 0260 return (x >> n) | (x << (16 - n)) 0261 } 0262 0263 func rotateRight
CryptoSwift.swift:131
                    let s0 = rotateRight(M[x-15], n: 7) ^ rotateRight(M[x-15], n: 18) ^ (M[x-15] >> 3) //FIXME: n
CryptoSwift.swift:131
                    let s0 = rotateRight(M[x-15], n: 7) ^ rotateRight(M[x-15], n: 18) ^ (M[x-15] >> 3) //FIXME: n
CryptoSwift.swift:132
                    let s1 = rotateRight(M[x-2], n: 17) ^ rotateRight(M[x-2], n: 19) ^ (M[x-2] >> 10)
CryptoSwift.swift:132
                    let s1 = rotateRight(M[x-2], n: 17) ^ rotateRight(M[x-2], n: 19) ^ (M[x-2] >> 10)
CryptoSwift.swift:149
                let s0 = rotateRight(A,n: 2) ^ rotateRight(A,n: 13) ^ rotateRight(A,n: 22)
CryptoSwift.swift:149
                let s0 = rotateRight(A,n: 2) ^ rotateRight(A,n: 13) ^ rotateRight(A,n: 22)
CryptoSwift.swift:149
                let s0 = rotateRight(A,n: 2) ^ rotateRight(A,n: 13) ^ rotateRight(A,n: 22)
CryptoSwift.swift:152
                let s1 = rotateRight(E,n: 6) ^ rotateRight(E,n: 11) ^ rotateRight(E,n: 25)
CryptoSwift.swift:152
                let s1 = rotateRight(E,n: 6) ^ rotateRight(E,n: 11) ^ rotateRight(E,n: 25)
CryptoSwift.swift:152
                let s1 = rotateRight(E,n: 6) ^ rotateRight(E,n: 11) ^ rotateRight(E,n: 25)
(x:UInt32, n:UInt32) -> UInt32 { 0264 return (x >> n) | (x << (32 - n)) 0265 } 0266 0267 func rotateRight(x:UInt64, n:UInt64) -> UInt64 { 0268 return ((x >> n) | (x << (64 - n))) 0269 } 0270 0271 0272 0273 /// Array of bytes, little-endian representation. Don't use if not necessary. 0274 /// I found this method slow 0275 func arrayOfBytes
CryptoSwift.swift:199
        return arrayOfBytes(self, length: totalBytes)
<T>(value:T, length:Int? = nil) -> [UInt8] { 0276 let totalBytes = length ?? sizeof(T) 0277 0278 let valuePointer = UnsafeMutablePointer<T>.alloc(1) 0279 valuePointer.memory = value 0280 0281 let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer) 0282 var bytes = [UInt8](count: totalBytes, repeatedValue: 0) 0283 for j in 0..<min(sizeof(T),totalBytes) { 0284 bytes[totalBytes - 1 - j] = (bytesPointer + j).memory 0285 } 0286 0287 valuePointer.destroy() 0288 valuePointer.dealloc(1) 0289 0290 return bytes 0291 } 0292 0293 /// Initialize integer from array of bytes. 0294 /// This method may be slow 0295 func integerWithBytes
CryptoSwift.swift:208
        return integerWithBytes(bytes)
<T: IntegerType where T:ByteConvertible, T: BitshiftOperationsType>(bytes: [UInt8]) -> T { 0296 var bytes = bytes.reverse() as Array<UInt8> //FIXME: check it this is equivalent of Array(...) 0297 if bytes.count < sizeof(T) { 0298 let paddingCount = sizeof(T) - bytes.count 0299 if (paddingCount > 0) { 0300 bytes += [UInt8](count: paddingCount, repeatedValue: 0) 0301 } 0302 } 0303 0304 if sizeof(T) == 1 { 0305 return T(truncatingBitPattern: UInt64(bytes.first!)) 0306 } 0307 0308 var result: T = 0 0309 for byte in bytes.reverse() { 0310 result = result << 8 | T(byte) 0311 } 0312 return result 0313 } 0314 0315 protocol BitshiftOperationsType
CryptoSwift.swift:295
func integerWithBytes<T: IntegerType where T:ByteConvertible, T: BitshiftOperationsType>(bytes: [UInt8]) -> T {
CryptoSwift.swift:327
extension Int    : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:328
extension Int8   : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:329
extension Int16  : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:330
extension Int32  : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:331
extension Int64  : BitshiftOperationsType, ByteConvertible {
CryptoSwift.swift:336
extension UInt   : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:337
extension UInt8  : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:338
extension UInt16 : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:339
extension UInt32 : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:340
extension UInt64 : BitshiftOperationsType, ByteConvertible {
{ 0316 func <<(lhs: Self, rhs: Self) -> Self 0317 func >>(lhs: Self, rhs: Self) -> Self 0318 func <<=(inout lhs: Self, rhs: Self) 0319 func >>=(inout lhs: Self, rhs: Self) 0320 } 0321 0322 protocol ByteConvertible
CryptoSwift.swift:295
func integerWithBytes<T: IntegerType where T:ByteConvertible, T: BitshiftOperationsType>(bytes: [UInt8]) -> T {
CryptoSwift.swift:327
extension Int    : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:328
extension Int8   : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:329
extension Int16  : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:330
extension Int32  : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:331
extension Int64  : BitshiftOperationsType, ByteConvertible {
CryptoSwift.swift:336
extension UInt   : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:337
extension UInt8  : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:338
extension UInt16 : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:339
extension UInt32 : BitshiftOperationsType, ByteConvertible { }
CryptoSwift.swift:340
extension UInt64 : BitshiftOperationsType, ByteConvertible {
{ 0323 init
CryptoSwift.swift:310
        result = result << 8 | T(byte)
(_ value: UInt8) 0324 init
CryptoSwift.swift:305
        return T(truncatingBitPattern: UInt64(bytes.first!))
(truncatingBitPattern: UInt64) 0325 } 0326 0327 extension Int : BitshiftOperationsType, ByteConvertible { } 0328 extension Int8 : BitshiftOperationsType, ByteConvertible { } 0329 extension Int16 : BitshiftOperationsType, ByteConvertible { } 0330 extension Int32 : BitshiftOperationsType, ByteConvertible { } 0331 extension Int64 : BitshiftOperationsType, ByteConvertible { 0332 init(truncatingBitPattern value: UInt64) { 0333 self = Int64(bitPattern: value) 0334 } 0335 } 0336 extension UInt : BitshiftOperationsType, ByteConvertible { } 0337 extension UInt8 : BitshiftOperationsType, ByteConvertible { } 0338 extension UInt16 : BitshiftOperationsType, ByteConvertible { } 0339 extension UInt32 : BitshiftOperationsType, ByteConvertible { } 0340 extension UInt64 : BitshiftOperationsType, ByteConvertible { 0341 init(truncatingBitPattern value: UInt64) { 0342 self = value 0343 } 0344 } 0345 0346 /** build bit pattern from array of bits */ 0347 func integerFromBitsArray<T: UnsignedIntegerType>(bits: [Bit]) -> T 0348 { 0349 var bitPattern:T = 0 0350 for (idx,b) in bits.enumerate() { 0351 if (b == Bit.One) { 0352 let bit = T(UIntMax(1) << UIntMax(idx)) 0353 bitPattern = bitPattern | bit 0354 } 0355 } 0356 return bitPattern 0357 } 0358 0359 protocol CSArrayType
CryptoSwift.swift:363
extension Array: CSArrayType {
CryptoSwift.swift:369
extension CSArrayType where Generator.Element == UInt8 {
: _ArrayType { 0360 func cs_arrayValue() -> [Generator.Element] 0361 } 0362 0363 extension Array: CSArrayType { 0364 func cs_arrayValue() -> [Generator.Element] { 0365 return self 0366 } 0367 } 0368 0369 extension CSArrayType where Generator.Element == UInt8 { 0370 0371 func toHexString
CryptoSwift.swift:379
        return self.arrayOfBytes().toHexString()
() -> String { 0372 return self.lazy.reduce("") { $0 + String(format:"%02x", $1) } 0373 } 0374 } 0375 0376 extension NSData { 0377 0378 func toHexString
SHA256Hasher.swift:22
            return NSData.withBytes(hmac).toHexString()
() -> String { 0379 return self.arrayOfBytes().toHexString() 0380 } 0381 0382 func arrayOfBytes
CryptoSwift.swift:379
        return self.arrayOfBytes().toHexString()
() -> [UInt8] { 0383 let count = self.length / sizeof(UInt8) 0384 var bytesArray = [UInt8](count: count, repeatedValue: 0) 0385 self.getBytes(&bytesArray, length:count * sizeof(UInt8)) 0386 return bytesArray 0387 } 0388 0389 convenience init(bytes: [UInt8]) { 0390 self.init(data: NSData.withBytes(bytes)) 0391 } 0392 0393 class func withBytes
CryptoSwift.swift:390
        self.init(data: NSData.withBytes(bytes))
SHA256Hasher.swift:22
            return NSData.withBytes(hmac).toHexString()
(bytes: [UInt8]) -> NSData { 0394 return NSData(bytes: bytes, length: bytes.count) 0395 } 0396 } 0397 0398 0399 class HMAC
SHA256Hasher.swift:21
        if let hmac = HMAC.authenticate(key: keyBuff, message: msgBuff) {
{ 0400 0401 class func calculateHash
CryptoSwift.swift:412
            if let hash = self.calculateHash(bytes: key) {
CryptoSwift.swift:432
        if let ipadAndMessageHash = self.calculateHash(bytes: ipad + message) {
CryptoSwift.swift:433
            finalHash = self.calculateHash(bytes: opad + ipadAndMessageHash);
(bytes bytes:[UInt8]) -> [UInt8]? { 0402 let sha = SHA2() 0403 sha.message = bytes 0404 return sha.calculate32() 0405 } 0406 0407 class func authenticate
SHA256Hasher.swift:21
        if let hmac = HMAC.authenticate(key: keyBuff, message: msgBuff) {
(key key: [UInt8], message: [UInt8]) -> [UInt8]? { 0408 var key = key 0409 0410 0411 if (key.count > 64) { 0412 if let hash = self.calculateHash(bytes: key) { 0413 key = hash 0414 } 0415 } 0416 0417 if (key.count < 64) { // keys shorter than blocksize are zero-padded 0418 key = key + [UInt8](count: 64 - key.count, repeatedValue: 0) 0419 } 0420 0421 0422 var opad = [UInt8](count: 64, repeatedValue: 0x5c) 0423 for (idx, _) in key.enumerate() { 0424 opad[idx] = key[idx] ^ opad[idx] 0425 } 0426 var ipad = [UInt8](count: 64, repeatedValue: 0x36) 0427 for (idx, _) in key.enumerate() { 0428 ipad[idx] = key[idx] ^ ipad[idx] 0429 } 0430 0431 var finalHash:[UInt8]? = nil; 0432 if let ipadAndMessageHash = self.calculateHash(bytes: ipad + message) { 0433 finalHash = self.calculateHash(bytes: opad + ipadAndMessageHash); 0434 } 0435 0436 return finalHash 0437 } 0438 0439 } 0440