Code Monkey home page Code Monkey logo

bluecryptor's Introduction

APIDoc Build Status - Master macOS iOS Linux Apache 2 Slack Status

BlueCryptor

Swift cross-platform crypto library derived from IDZSwiftCommonCrypto.

IMPORTANT NOTE: This release is NOT entirely source code compatible with previous releases. There are instances where exceptions are thrown now instead of the framework calling fatalError(). This means that there are more recoverable errors in the library than before. The only time that fatalError() is called is to indicate either a programming error or a non-recoverable system error.

Note: On macOS and iOS, BlueCryptor uses the Apple provided CommonCrypto library. On Linux, it uses libcrypto from the OpenSSL project.

Prerequisites

Swift

  • Swift Open Source swift-5.1-RELEASE toolchain (Minimum REQUIRED for latest release)
  • Swift Open Source swift-5.4-RELEASE toolchain (Recommended)
  • Swift toolchain included in Xcode Version 11.0 or higher.

macOS

  • macOS 10.14.6 (Mojave) or higher.
  • Xcode Version 11.0 or higher using one of the above toolchains.
  • Xcode Version 12.5 or higher using the included toolchain (Recommended).
  • CommonCrypto is provided by macOS.

iOS

  • iOS 10.0 or higher
  • Xcode Version 11.0 or higher using one of the above toolchains.
  • Xcode Version 12.5 or higher using the included toolchain (Recommended).
  • CommonCrypto is provided by iOS.

Linux

  • Ubuntu 16.04 (or 16.10 but only tested on 16.04) and 18.04.
  • One of the Swift Open Source toolchain listed above.
  • OpenSSL is provided by the distribution. Note: 1.0.x, 1.1.x and later releases of OpenSSL are supported.
  • The appropriate libssl-dev package is required to be installed when building.

Build

To build Cryptor from the command line:

% cd <path-to-clone>
% swift build

Testing

To run the supplied unit tests for Cryptor from the command line:

% cd <path-to-clone>
% swift build
% swift test

Getting started

Including in your project

Swift Package Manager

To include BlueCryptor into a Swift Package Manager package, add it to the dependencies attribute defined in your Package.swift file. You can select the version using the majorVersion and minor parameters. For example:

	dependencies: [
		.Package(url: "https://github.com/Kitura/BlueCryptor.git", majorVersion: <majorVersion>, minor: <minor>)
	]

Carthage

To include BlueCryptor in a project using Carthage, add a line to your Cartfile with the GitHub organization and project names and version. For example:

	github "Kitura/BlueCryptor" ~> <majorVersion>.<minor>

CocoaPods

To include BlueCryptor in a project using CocoaPods, you just add BlueCryptor to your Podfile, for example:

    platform :ios, '10.0'

    target 'MyApp' do
        use_frameworks!
        pod 'BlueCryptor'
    end

Before starting

The first thing you need to do is import the Cryptor framework. This is done by the following:

import Cryptor

API

Cryptor

The following code demonstrates encryption and decryption using AES single block CBC mode using optional chaining.

let key = CryptoUtils.byteArray(fromHex: "2b7e151628aed2a6abf7158809cf4f3c")
let iv = CryptoUtils.byteArray(fromHex: "00000000000000000000000000000000")
let plainText = CryptoUtils.byteArray(fromHex: "6bc1bee22e409f96e93d7e117393172a")

var textToCipher = plainText
if plainText.count % Cryptor.Algorithm.aes.blockSize != 0 {
	textToCipher = CryptoUtils.zeroPad(byteArray: plainText, blockSize: Cryptor.Algorithm.aes.blockSize)
}
do {
	let cipherText = try Cryptor(operation: .encrypt, algorithm: .aes, options: .none, key: key, iv: iv).update(byteArray: textToCipher)?.final()
		
	print(CryptoUtils.hexString(from: cipherText!))
		
	let decryptedText = try Cryptor(operation: .decrypt, algorithm: .aes, options: .none, key: key, iv: iv).update(byteArray: cipherText!)?.final()

	print(CryptoUtils.hexString(from: decryptedText!))
} catch let error {
	guard let err = error as? CryptorError else {
		// Handle non-Cryptor error...
		return
	}
	// Handle Cryptor error... (See Status.swift for types of errors thrown)
}

Digest

The following example illustrates generating an MD5 digest from both a String and an instance of NSData.

let qbfBytes : [UInt8] = [0x54,0x68,0x65,0x20,0x71,0x75,0x69,0x63,0x6b,0x20,0x62,0x72,0x6f,0x77,0x6e,0x20,0x66,0x6f,0x78,0x20,0x6a,0x75,0x6d,0x70,0x73,0x20,0x6f,0x76,0x65,0x72,0x20,0x74,0x68,0x65,0x20,0x6c,0x61,0x7a,0x79,0x20,0x64,0x6f,0x67,0x2e]
let qbfString = "The quick brown fox jumps over the lazy dog."

// String...
let md5 = Digest(using: .md5)
md5.update(string: qfbString)
let digest = md5.final()

// NSData using optional chaining...
let qbfData = CryptoUtils.data(from: qbfBytes)
let digest = Digest(using: .md5).update(data: qbfData)?.final()

HMAC

The following demonstrates generating an SHA256 HMAC using byte arrays for keys and data.

let myKeyData = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"
let myData = "4869205468657265"
let key = CryptoUtils.byteArray(fromHex: myKeyData)
let data : [UInt8] = CryptoUtils.byteArray(fromHex: myData)

let hmac = HMAC(using: HMAC.Algorithm.sha256, key: key).update(byteArray: data)?.final()

Key Derivation

The following illustrates generating a key using a password, salt, number of rounds and a specified derived key length using the SHA1 algorithm. Then it shows how to generate a String from resultant key.

let password = "password"
let salt = salt
let rounds: UInt = 2
let derivedKeyLen = 20
do {
	let key = PBKDF.deriveKey(fromPassword: password, salt: salt, prf: .sha1, rounds: rounds, derivedKeyLength: derivedKeyLen)
	let keyString = CryptoUtils.hexString(from: key)
} catch let error {
	guard let err = error as? CryptorError else {
		// Handle non-Cryptor error...
		return
	}
	// Handle Cryptor error... (See Status.swift for types of errors thrown)
}

Random Byte Generation

The following demonstrates generating random bytes of a given length.

let numberOfBytes = 256*256
do {
	let randomBytes = try Random.generate(byteCount: numberOfBytes)
} catch {
  	print("Error generating random bytes")
}

Utilities

Cryptor also provides a set of data manipulation utility functions for conversion of data from various formats:

  • To byteArray ([UInt8])
    • From hex string
    • From UTF8 string
  • To Data
    • From hex string
    • From byte array ([UInt8])
  • To NSData
    • From hex string
    • From byte array ([UInt8])
  • To NSString
    • From byte array ([UInt8])
  • To hexList (String)
    • From byte array ([UInt8])

Also provided are an API to pad a byte array ([UInt8]) such that it is an integral number of block size in bytes long.

  • func zeroPad(byteArray: [UInt8], blockSize: Int) -> [UInt8]
  • func zeroPad(string: String, blockSize: Int) -> [UInt8]

Restrictions

The following algorithm is not available on Linux since it is not supported by OpenSSL.

  • Digest: MD2

In all cases, use of unsupported APIs or algorithms will result in a Swift fatalError(), terminating the program and should be treated as a programming error.

Community

We love to talk server-side Swift and Kitura. Join our Slack to meet the team!

License

This library is licensed under Apache 2.0. Full license text is available in LICENSE.

bluecryptor's People

Contributors

alexpersian avatar andrew-lees11 avatar bdhernand avatar billabt avatar dannys42 avatar djones6 avatar giginet avatar helenmasters avatar ianpartridge avatar joebayld avatar kyemaloy97 avatar mman avatar quanvo87 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bluecryptor's Issues

error: manifest parse error(s): The manifest file at https://github.com/IBM-Swift/CommonCrypto.git (0.1.3) is empty

I cleaned up the last build. the following is my package.swift

let package = Package(
name: "openActivity",
dependencies: [
.package(url: "https://github.com/IBM-Swift/Kitura.git", .upToNextMinor(from: "2.0.0")),
.package(url: "https://github.com/IBM-Swift/HeliumLogger.git", .upToNextMajor(from: "1.0.0")),
.package(url: "https://github.com/IBM-Swift/BlueCryptor.git", .upToNextMajor(from: "0.8.0")),
.package(url: "https://github.com/IBM-Swift/Kitura-Session.git", .upToNextMinor(from: "2.0.0")),
.package(url: "https://github.com/IBM-Swift/Swift-Kuery.git", .upToNextMajor(from: "1.0.0")),
.package(url: "https://github.com/IBM-Swift/SwiftKueryMySQL.git", .upToNextMajor(from: "1.0.0")),
],
targets: [
.target(
name: "openActivity",
dependencies: ["Kitura", "KituraSession", "HeliumLogger", "Cryptor", "SwiftKuery", "SwiftKueryMySQL" ]),
]
)

but I still get the same error:
error: manifest parse error(s): The manifest file at https://github.com/IBM-Swift/CommonCrypto.git (0.1.3) is empty

Error on import Cryptor using Swift 4 on Linux

Hi there,

This is likely operator error, but I didn't see any tickets related and thought I'd see if I'm doing something obviously wrong. I'm trying to use the Cryptor package via Swift package manager for a command line executable on Ubuntu 16.04 using swift-4.0-DEVELOPMENT-SNAPSHOT-2017-07-24-a-ubuntu16.04, but I can't seem to get the package dependency to take.

I set things up like so:

mkdir rando
cd rando
swift package init --type executable

The Package.swift file for my new project:

// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "rando",
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
        .package(url: "https://github.com/IBM-Swift/BlueCryptor.git", from: "0.8.16")
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "rando",
            dependencies: []),
    ]
)

The main.swift file head:

import Glibc
import Foundation
import Cryptor

When I run swift build things appear to go as planned but the compiler errors out on the import statement:

wgray@ubuntu:~/Swift/rando$ swift build
Fetching https://github.com/IBM-Swift/BlueCryptor.git
Updating https://github.com/IBM-Swift/BlueCryptor
Updating https://github.com/IBM-Swift/OpenSSL.git
Cloning https://github.com/IBM-Swift/BlueCryptor.git
Resolving https://github.com/IBM-Swift/BlueCryptor.git at 0.8.16
Compile Swift Module 'rando' (1 sources)
/home/wgray/Swift/rando/Sources/rando/main.swift:3:8: error: no such module 'Cryptor'
import Cryptor
       ^
error: terminated(1): /home/wgray/swift-4.0-DEVELOPMENT-SNAPSHOT-2017-07-24-a-ubuntu16.04/usr/bin/swift-build-tool -f /home/wgray/Swift/rando/.build/debug.yaml main

Perhaps I missed a step, or need to provide some kind of module map listing? Another thought that occurs is that I've had to provide flags to the compiler and linker in other situations, am I missing something I should be passing, e.g. swift build -Xcc -DENABLE_FOO ?

Thanks for any advice, and apologies if there is another more preferable place to post questions like this.

Request: Random.generate(hexCharacterCount:)

The Random.generate(byteCount:) is a useful way of generating random bytes, but in my own work I found I was mostly using it to generate random strings for encryption purposes. This meant every call to Random.generate(byteCount:) was followed by a call to CryptoUtils.hexString(from:) to get a Swift string rather than just bytes.

If you could implement a Random.generate(hexCharacterCount:) method that combined the two together, it would be most appreciated. If this were combined with #17, then this code:

if let randomBytes = try? Random.generate(byteCount: 64) {
    randomString = CryptoUtils.hexString(from: randomBytes)
} else {
    randomString = generateMyOwnRandomStringSomehow()
}

Would become simply this:

randomString = Random.generate(hexCharacterCount: 128)

(Note: There may well be a better name for this method.)

swift build warning (misuse EVP_DecryptFinal | EVP_EncryptFinal)

Ubuntu 18.04
Swift 5.0

$ swift build -c release 

// console logs:

.../.build/x86_64-unknown-linux/release/Cryptor.build/StreamCryptor.swift.o:Crypto.swift.o:function $s7Cryptor06StreamA0C5final9bufferOut012byteCapacityE00f5CountE0AA6StatusOSpys5UInt8VG_S2iztFTf4nnnn_g: warning: EVP_DecryptFinal is often misused, please use EVP_DecryptFinal_ex and EVP_CIPHER_CTX_cleanup

.../.build/x86_64-unknown-linux/release/Cryptor.build/StreamCryptor.swift.o:Crypto.swift.o:function $s7Cryptor06StreamA0C5final9bufferOut012byteCapacityE00f5CountE0AA6StatusOSpys5UInt8VG_S2iztFTf4nnnn_g: warning: EVP_EncryptFinal is often misused, please use EVP_EncryptFinal_ex and EVP_CIPHER_CTX_cleanup

Screen Shot

Invalid Triple-DES encryption result

Hi everyone,

I'm going to implement the Triple-DES to encrypt a password and I'm using the following command to validate the encryption output.
Screen Shot 2022-06-01 at 3 47 48 PM

but I got a different encryption result.

Here's my code

func tripleDesEncrypt(inputStr: String, keyStr: String) -> String? {
        let key = CryptoUtils.byteArray(fromHex: keyStr)
        let iv = CryptoUtils.byteArray(fromHex: "0000000000000000")
        let plainText = CryptoUtils.byteArray(fromHex: inputStr)
        
        var textToCipher = plainText
        if plainText.count % Cryptor.Algorithm.tripleDes.blockSize != 0 {
            textToCipher = CryptoUtils.zeroPad(byteArray: plainText, blockSize: Cryptor.Algorithm.tripleDes.blockSize)
        }
        do {
            let cipherText = try Cryptor(operation: .encrypt, algorithm: .tripleDes, options: .pkcs7Padding, key: key, iv: iv).update(byteArray: textToCipher)?.final()
            
            print(CryptoUtils.hexString(from: cipherText!))

        } catch let error {
            guard let err = error as? CryptorError else {
                return nil
            }
            
            print(err.description)
        }
        
        return nil
    }

Input
inputStr: 0592389EDCBA96FF
keyStr: 0123456789abcdeffedcba9876543210

Output
d9f8e02413307c829b81df2a39d8c603

The right output should be
a25fbc3a3ed409102e24eeb85aef49ae

Please advise.

Multiple free() bug in StreamCryptor.swift

With a long-lived Kitura processes using encrypted cookies, StreamCryptors get created and torn down many times as requests come in.

As per http://openssl.6102.n7.nabble.com/Multiple-calls-to-ERR-load-crypto-string-td4591.html ERR_free_strings() cannot be safely called in between calls to ERR_load_crypto_strings() without causing memory corruption.

More info (and full stack trace) at https://github.com/IBM-Swift/sandbox-ui/issues/119

Shortened stack trace:
REDACTEDCrash.txt

Can Random.generate() be non-throwing?

When I need to generate some random data for a string, I'd run code like this:

if let randomBytes = try? Random.generate(byteCount: 64) {
    randomString = CryptoUtils.hexString(from: randomBytes)
} else {
    randomString = generateMyOwnRandomStringSomehow()
}

If I'm trying to generate something important, e.g. a salt, the generateMyOwnRandomStringSomehow() is a weak point because it relies on users to have some idea of PRNG techniques. Is it possible to make Random.generate() always return a value, perhaps by implementing a second generation algorithm that can be used if the preferred algorithm fails?

(Note: the answer may well be "No", but I'm following the "if you don't ask, you don't get" approach.")

CHTTParser error when running swift build

Hi guys,

So i am a newbie, and in my environment, im running Kaitura over Docker. I get the following error, which I believe is related to the Crypto library, when i run swift build:

/projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ Compile Swift Module 'LoggerAPI' (1 sources) /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ Compile Swift Module 'Core' (28 sources) Compile Swift Module 'Node' (22 sources) /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ /projects/project7/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include' not found umbrella "/Users/doronkatz/Development/Server/project7/Packages/CHTTPParser-0.3.0/Sources/CHTTPParser/include" ^ <unknown>:0: error: build had 5 command failures error: exit(1): /root/swift-3.0.1-RELEASE-ubuntu16.04/usr/bin/swift-build-tool -f /projects/project7/.build/debug.yaml

My Package.swift is as follows:

`
import PackageDescription

let package = Package(
name: "project7",
dependencies: [
.Package(url: "https://github.com/IBM-Swift/Kitura.git", majorVersion: 1),
.Package(url: "https://github.com/IBM-Swift/HeliumLogger.git", majorVersion: 1),
.Package(url: "https://github.com/IBM-Swift/BlueCryptor.git", majorVersion: 0, minor: 8),
.Package(url: "https://github.com/vapor/mysql.git", majorVersion: 1),
]
)
`

Im on Swift 3.0.1. Not sur what else I can do on my end... Any assistance would be great. When i took out crypto the build worked.

Thanks!

Request: OpenSSL 1.1 support

I know this is a "known issue" so to speak as it's made clear in the readme that only OpenSSL 1.0 is supported currently but this version is not available in distributions of linux such as Debian Stretch.

A workaround for Debian Stretch is to install libssl1.0 and libssl1.0-dev.
The libssl1.0-dev package has the nasty side-effect of removing libssl1.1-dev as they cannot exist side by side unlike the libssl1.0 and libssl1.1 library themselves.

CMS Signatures

Would it be possible to get CMS/PKCS#7 signatures (both attached and detached) added to BlueCrypto? This would be useful for signing MDM payloads, validating AppStore receipts, etc. It's also unsupported by any Swift Linux framework.

How can I get the same output with openssl?

I use the code below to encrypt my data

static func encryptToBase64(text: String, keyInHex: String) -> String? {
        let key = CryptoUtils.byteArray(fromHex: keyInHex)
        let plainText = CryptoUtils.byteArray(from: text)
        
        var textToCipher = plainText
        if plainText.count % Cryptor.Algorithm.aes.blockSize != 0 {
            textToCipher = CryptoUtils.zeroPad(byteArray: plainText, blockSize: Cryptor.Algorithm.aes.blockSize)
        }
        do {
            let cipherText = try Cryptor(operation: .encrypt, algorithm: .aes, options: [.ecbMode, .none], key: key, iv: []).update(byteArray: textToCipher)?.final()
            if let cipherText = cipherText {
                return Data(bytes: cipherText).base64EncodedString()
            }
        } catch {
       
        }
        return nil
    }

And with my test data:

let hexKey = "3466306662616434373134316566393631366365346437316234353965656139"
let plain = "0123456789abcdeffedcba9876543210"

encryptToBase64(text: plain, keyInHex: hexKey) returns "Zt+9JdbWYOp+QHagRwOdWYrtWIlohN+QR8anoAaZeiE="
Meanwhile, the ouput of an equivalent OpenSSL

echo -n "0123456789abcdeffedcba9876543210" | openssl enc -e -aes-128-ecb -K "3466306662616434373134316566393631366365346437316234353965656139" -a -nopad

is "EdlbUs/uJ5b7Ww4YaybT0MT5+nEO5NMA41LBgA1/sfA="

Why they are not the same? And could you show me how to get the same output with OpenSSL?

RSA Signing

What would it take to extend this library to support RSA in addition to HMAC? I'd like to use it for signing JWT tokens, but Google only supports RS256.

Looks like CommonCrypto supports it, so I'm assuming OpenSSL does too.

ECDSA support

In SwiftJWT, we would like to support ES256. This requires the JWT be signed/verified using ECDSA. BlueCryptor seems like the right place to implement a common API for the Elliptic curve algorithm.

OpenSSL has an implementation that is documented here. This could be used for the linux implementation.

Apple security has an implementation that is documented here. This could be used for the iOS/MacOS implementation.

@billabt This approach is fairly similar to BlueRSA. Is there a reason you made BlueRSA a separate repo instead of incorporating it into BlueCryptor?

Version-specific manifest not support latest Swift 5

The package can not be resolved in Swift 5.

It is not expected the packages would ever use this feature unless absolutely necessary to support existing clients. In particular, packages should not adopt this syntax for tagging versions supporting the latest GM Swift version.

Getting " " (empty) Decrypted string from update function

class func decrypt(encodedData: String, secret: String, algorithm: String) -> String {
        do {
            let key = Array(secret.utf8)
            let bytes = encodedData.hexaBytes
            let cryptor = try Cryptor(operation:.decrypt, algorithm:.aes256, options:[.ecbMode, .pkcs7Padding], key:key, iv:[UInt8]())
            if let decrypted = cryptor.update(byteArray: bytes)?.final() {
                return String(bytes: decrypted, encoding: .utf8) ?? ""
            }
        } catch {
            print(error)
        }
        return ""
}

i am using above function to decrypt data. it will returning blank "" string.
i am using .ecbMode and .pkcs7Padding pattern
also i am getting key and bytes data successfully. issue in cryptor.update function.

Remove support for deprecated cryptographic options (MD2, MD4, MD5) & release to cocoapods

Looks like Apple is considering MD2, MD4, M5 "cryptographically broken"

'CC_MD2_Final' was deprecated in iOS 13.0: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).

So, might as well remove those options.

Then, once the options are removed - would be awesome to release the new version to cocoapods! πŸ˜„

(working on a PR to address, now)

-Thanks!

Cryptor-iOS Scheme is not Shared

Because the scheme is not shared, I cannot do a build with Carthage. Would you mind making sure the scheme is shared as are the other two?

Fresh checkout won't build

I just did a checkout of the project:

commit 7865ad2f864633eb945dc77c43213fb34688bb3e
Author: Bill Abt <[email protected]>
Date:   Mon Jun 25 11:59:50 2018 -0400

OS

developer@ubuntu:~/Repositories/github.com/IBM-swift/BlueCryptor$ lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 16.04.4 LTS
Release:	16.04
Codename:	xenial

Toolchain

developer@ubuntu:~/Repositories/github.com/IBM-swift/BlueCryptor$ swift --version
Swift version 4.1.2 (swift-4.1.2-RELEASE)
Target: x86_64-unknown-linux-gnu

Details

After running

swift build

I get:

Compile Swift Module 'Cryptor' (10 sources)
<module-includes>:1:10: note: in file included from <module-includes>:1:
#include "shim.h"
         ^
/home/developer/Repositories/github.com/IBM-swift/BlueCryptor/.build/checkouts/OpenSSL.git--6385253650136148626/shim.h:20:10: error: 'openssl/conf.h' file not found
#include <openssl/conf.h>
         ^
/home/developer/Repositories/github.com/IBM-swift/BlueCryptor/Sources/Cryptor/Digest.swift:23:9: error: could not build C module 'OpenSSL'
        import OpenSSL
               ^
error: terminated(1): /opt/swift-4.1.2/usr/bin/swift-build-tool -f /home/developer/Repositories/github.com/IBM-swift/BlueCryptor/.build/debug.yaml main output:

PBKDF derivation compiler warning

I'm having a problem with the following usage

key = try PBKDF.deriveKey(fromPassword:password, salt: salt,
                               prf: .sha512, rounds: 1000,
                               derivedKeyLength: 256)

The compiler is telling me I have an "Ambiguous reference to member 'deriveKey(fromPassword:salt:prf:rounds:derivedKeyLength:)'

password is a String
salt is a [UInt8]
the other values are as expected

I expected the string parameter for password to enable the compiler to disambiguate the call. This is with Swift 5.0

Any thoughts? For now I'll access commoncrypto instead.

Detect Invalid Initialization Vector Size.

Since this code is based on IDZSwiftCommonCrypto it has inherited some of that library's flaws. While the library currently pays quite a bit of attention to keys, it has no error checking on IV size.

If a user supplies too small an IV, some uninitialized bytes will used by CommonCrypto. This is not a security risk, it just leads to incorrect results and difficult to track down bugs.

We're adding additional error checking to try to catch these problems before they occur.

You may want to take a look at iosdevzone/IDZSwiftCommonCrypto#79 to see the changes we're making!

error: manifest parse error(s): The manifest file at https://github.com/IBM-Swift/CommonCrypto.git (0.1.3) is empty

the version of swift is 4.0.3, on macOS(4.0.3) it returns the error message, on linux(4.0.3) it is just stuck while downloading dependencies. there is the whole file of package.swift:

// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "openActivity",
    dependencies: [
        .package(url: "https://github.com/IBM-Swift/Kitura.git", .upToNextMinor(from: "2.0.0")),
        .package(url: "https://github.com/IBM-Swift/HeliumLogger.git", .upToNextMinor(from: "1.7.1")),
        .package(url: "https://github.com/IBM-Swift/Kitura-Session.git", .upToNextMinor(from: "2.0.0")),
        .package(url: "https://github.com/IBM-Swift/Swift-Kuery.git", .upToNextMajor(from: "1.0.0")),
        .package(url: "https://github.com/IBM-Swift/SwiftKueryMySQL.git", .upToNextMajor(from: "1.0.0")),
    ],
    targets: [
        .target(
            name: "openActivity",
            dependencies: ["Kitura", "HeliumLogger", "KituraSession", "SwiftKuery", "SwiftKueryMySQL"]),
    ]
)

Replace some fatalError's by optional/Result/throws

I'm using Cryptor for doing signed+encrypted cookies, as well as encrypted values in url params, for example an unsubscribe link in an email that allows quick removal from newsletters.

The library currently fatalError's a lot. Some of it seems reasonable, like using an unsupported encryption algorithm. However, fatalError's are also used for malformed data, which could happen if the user tampers with cookies, urls, etc... This means a user can crash a server using Cryptor very easily.

Should all uses of fatalError be audited to convert most to use optionals, Result or throws?

Updating with Data

Line 65 of Updatable.swift - is there any reason data needs to be inout?

public func update(data: inout Data) -> Self? 

It makes this method unusable with immutable Data objects. The pointer generated in the closure is immutable so I don't see a reason to force the inout argument.

Xcode 10 Support

The new SDK supports CommonCrypto out of the box, preventing builds due to duplicate headers.

Minor release for swift 4.1

Could we get a minor release to fix errors for swift 4.1 please? Code is already in master ...

The warnings are staining our otherwise yellow free project :)

Installing via CocoaPods results in error "No such module 'CommonCrypto'"

Perhaps CocoaPods is not yet fully supported since the Podspec is not published in the cocoapods source
repo. I tried doing this:

pod 'BlueCryptor', :git => 'https://github.com/IBM-Swift/BlueCryptor.git', :commit => '30b6cf38322838d1e973e0626c6abf9602b03cf5'

Building the project then throws this error:

No such module 'CommonCrypto'

in Digest.swift:21

Are there plans for more detailed installation instructions?

p.s. I'm using swift 4.1 on xcode 9.4.2 / ios 11, which doesn't yet have the CommonCrypto package.. My understanding is that it requires a bridging header.

HMAC-SHA1 Linux compatibility

The docs here say that HMAC-SHA1 is not supported by OpenSSL. However, as far as I can see it does appear to be supported (Ubuntu 16.04):

echo -n "value" | openssl dgst -sha1 -hmac "key"
>> 57443a4c052350a44638835d64fd66822f813319

Am I missing something? It would be great to use this for OAuth1. Thanks.

iOS Support

Hi @billabt Thanks for assembling this fantastic framework!

I'm using it on Linux fine. I now want to integrate it into my iOS app. iOS support is listed on the README, but integration is proving difficult. The Xcode project in the git repo seems to be configured for macOS; it produces a dylib. I have not yet succeeded at getting this dylib to build my iOS app which depends on Cryptor. Can you confirm that this project actually supports iOS integration? Do you have a sample iOS project that I can reference?

Request: add equivalents to PHP's password_hash() and password_verify() functions

Everyone knows secure coding is hard, so it's very helpful that BlueCryptor provides a great deal of advanced functionality to make a developer's life easier. Sadly, even with helpful API around, using them badly results in an insecure project – in fact one could even argue that it's less secure, because its developers have a false sense of security in their poor implementation. (Probably the most famous example, from some years ago.)

When it comes to storing passwords, PHP has two excellent functions that take a lot of the worry away from developers: password_hash() and password_verify(). The former accepts a plain text password as its first parameter, and created a password hash using Blowfish. To make this work, it also creates a salt for you. The complete string that gets returned contains the algorithm that was used, salt, and cost (presumably rounds?) as part of the hash, which means it's a single value that can be stored in a database attached to a user.

When it comes time to authenticate the user, password_verify() is used. This takes the plain-text password from the user along with the hash string returned from password_hash(), and returns true if they match. This is possible because password_hash() contains all the extra information – validation is pretty simple.

Storing important information such as passwords is always going to be an important part of any web project. As a result, it would be helpful if BlueCryptor added functions similar to these two from PHP that effectively eliminate a wide variety of coder errors and ensure best practice.

custom framework build failing with no full bitcode error

Hi Everyone,
I am very new to iOS so this might be a stupid question, but please help me out. I am using the BlueCryptor for doing some encryptions in my custom framework. I added the BlueCryptor to the framework through SwiftPackages->AddNewPackage. All the functionality is working fine.

I am using my framework in an app which needs bitcode to be enabled. So I added this user-defined build setting in my fraework: BITCODE_GENERATION_MODE(https://medium.com/@heitorburger/static-libraries-frameworks-and-bitcode-6d8f784478a9)

Now the build is failing with :

ld: bitcode bundle could not be generated because '/Users/ds/Library/Developer/Xcode/DerivedData/customFramework-excnpjvylyjcgnahfenjtaqmjjmf/Build/Products/Release-iphoneos/Cryptor.o' was built without full bitcode. All object files and libraries for bitcode must be generated from Xcode Archive or Install build file '/Users/ds/Library/Developer/Xcode/DerivedData/customFramework-excnpjvylyjcgnahfenjtaqmjjmf/Build/Products/Release-iphoneos/Cryptor.o' for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Invalid Exclude in Xcode 13

Since upgrading to Xcode 13, I'm seeing an Invalid Exclude warning message indicating that the requested file cannot be found.

This applies to:

  • Cryptor.xcodeproj
  • Sources/Info.plist
  • README.md

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.