Skip to content

Commit

Permalink
fix: Use PKCS7 padding for cookie cryptor (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrew-Lees11 authored Mar 11, 2019
1 parent bb7b535 commit 6e73282
Showing 1 changed file with 3 additions and 17 deletions.
20 changes: 3 additions & 17 deletions Sources/KituraSession/CookieCryptography.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,6 @@ class CookieCryptography {
///
private var signatureKey: [UInt8]

///
/// Length of cookie value before padding
///
private let originalLength = 36

init (secret: String) throws {
let encryptionKeySalt = "If two witches would watch two watches, which witch would watch which watch?"
let signatureKeySalt = "Six sick hicks nick six slick bricks with picks and sticks."
Expand All @@ -63,14 +58,9 @@ class CookieCryptography {
}

let plainData = CryptoUtils.byteArray(from: plain)
var dataToCipher = plainData
// Padding
if plainData.count % Cryptor.Algorithm.aes.blockSize != 0 {
dataToCipher = CryptoUtils.zeroPad(byteArray: plainData, blockSize: Cryptor.Algorithm.aes.blockSize)
}

do {
guard let cipherData = try Cryptor(operation: .encrypt, algorithm: .aes, options: .none, key: encryptionKey, iv: iv).update(byteArray: dataToCipher)?.final() else {
guard let cipherData = try Cryptor(operation: .encrypt, algorithm: .aes, options: .pkcs7Padding, key: encryptionKey, iv: iv).update(byteArray: plainData)?.final() else {
Log.error("Failed to encrypt cookie")
return nil
}
Expand Down Expand Up @@ -124,16 +114,12 @@ class CookieCryptography {
// Decryption
do {

guard let decryptedData = try Cryptor(operation: .decrypt, algorithm: .aes, options: .none, key: encryptionKey, iv: iv).update(byteArray: cipherData)?.final() else {
guard let decryptedData = try Cryptor(operation: .decrypt, algorithm: .aes, options: .pkcs7Padding, key: encryptionKey, iv: iv).update(byteArray: cipherData)?.final() else {
Log.error("Failed to decrypt cookie")
return nil
}

var resultData = decryptedData
// Remove padding
resultData.removeSubrange(originalLength ..< decryptedData.count)

return String(data: Data(bytes: resultData), encoding: .utf8)
return String(data: Data(bytes: decryptedData), encoding: .utf8)

} catch {
Log.error("Error decoding cookie: \(error)")
Expand Down

0 comments on commit 6e73282

Please sign in to comment.