var crypto = require('crypto'); var data = "Lorem ipsum dolor sit amet"; var key = newBuffer('12345678901234567890123456789012'); var iv = crypto.randomBytes(16); var cipher = crypto.createCipheriv('aes-256-cbc', key, iv); var encrypted = cipher.update(data, 'utf-8'); encrypted = Buffer.concat([iv, encrypted, cipher.final()]); return res.json({ encryptedToken: encrypted.toString('hex') });
funcdecrypt(encryptedString: String) -> String? { let key = [UInt8]("12345678901234567890123456789012".utf8)
let ivRange =NSMakeRange(0, 32) let iv = hexStringToUInt8(encryptedString, range: ivRange)
let dataLength = encryptedStr.characters.count -32 if dataLength <0 { returnnil } let dataRange =NSMakeRange(32, dataLength) let data = hexStringToUInt8(encryptedStr, range: dataRange) do { let aes =tryAES(key: key, iv: iv, blockMode: .CBC) let decrypted =try aes.decrypt(data) let result = convertUInt8ToUTF(decrypted) return result } catchlet error asNSError { debugPrint(error) returnnil } }
// http://stackoverflow.com/questions/24465475/how-can-i-create-a-string-from-utf8-in-swift funcconvertUInt8ToUTF(bytes:[UInt8]) -> String { var ret ="" var decoder =UTF8() var generator = bytes.generate() var finished =false repeat { let decodingResult = decoder.decode(&generator) switch decodingResult { case .Result(let char): ret.append(char) default: finished =true } } while (!finished) return ret }
funchexStringToUInt8(str:String, range:NSRange) -> [UInt8]{ let nsstr:NSString= (str asNSString).substringWithRange(range) let strLength =String(nsstr).characters.count var result:[UInt8] = []
for(var i=0; i<strLength; i +=2){ let r =NSMakeRange(i, 2) let substr = nsstr.substringWithRange(r) result.append(UInt8(strtoul(substr, nil, 16))) }