Skip to content

Commit

Permalink
Prevent from appending CryptorHeader for LegacyCryptor used as an enc…
Browse files Browse the repository at this point in the history
…oder
  • Loading branch information
jguz-pubnub committed Sep 29, 2023
1 parent 7726ea6 commit 83ba71f
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 11 deletions.
17 changes: 11 additions & 6 deletions Sources/PubNub/Helpers/Crypto/CryptorModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,14 @@ public struct CryptorModule {

public func encrypt(data: Data) -> Result<Data, PubNubError> {
defaultCryptor.encrypt(data: data).map {
CryptorHeader.v1(
cryptorId: defaultCryptor.id,
data: $0.metadata
).asData() + $0.data
if defaultCryptor.id == LegacyCryptor.ID {
return $0.data
} else {
return CryptorHeader.v1(
cryptorId: defaultCryptor.id,
data: $0.metadata
).asData() + $0.data
}
}.mapError {
PubNubError(.encryptionError, underlying: $0)
}
Expand Down Expand Up @@ -99,10 +103,11 @@ public struct CryptorModule {
stream: stream,
contentLength: contentLength
).map {
let header = CryptorHeader.v1(
let header = defaultCryptor.id != LegacyCryptor.ID ? CryptorHeader.v1(
cryptorId: defaultCryptor.id,
data: $0.metadata
)
) : .none

let multipartInputStream = MultipartInputStream(
inputStreams: [InputStream(data: header.asData()), $0.stream]
)
Expand Down
8 changes: 4 additions & 4 deletions Sources/PubNub/Helpers/Crypto/Cryptors/LegacyCryptor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ import CommonCrypto
public struct LegacyCryptor: Cryptor {
private let key: Data
private let withRandomIV: Bool

static let legacyCryptorId: CryptorId = [0x00, 0x00, 0x00, 0x00]

static let ID: CryptorId = [0x00, 0x00, 0x00, 0x00]
public init(key: String, withRandomIV: Bool = true) {
let hash = CryptorUtils.SHA256.hash(from: key.data(using: .utf8) ?? Data())
let hexStrData = CryptorUtils.hexFrom(hash).lowercased(with: .current).data(using: .utf8) ?? Data()
Expand All @@ -42,7 +42,7 @@ public struct LegacyCryptor: Cryptor {
}

public var id: CryptorId {
Self.legacyCryptorId
Self.ID
}

public func encrypt(data: Data) -> Result<EncryptedData, Error> {
Expand Down
2 changes: 1 addition & 1 deletion Sources/PubNub/Helpers/Crypto/Header/CryptorHeader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ enum CryptorHeader: Equatable {
func cryptorId() -> CryptorId {
switch self {
case .none:
return LegacyCryptor.legacyCryptorId
return LegacyCryptor.ID
case .v1(let cryptorId, _):
return cryptorId
}
Expand Down

0 comments on commit 83ba71f

Please sign in to comment.