12/08/2018, 14:19

Symmetric Cryptography in Swift (BlowFish)

Blowfish is a symmetric-key block cipher, designed in 1993 by Bruce Schneier and included in a large number of cipher suites and encryption products. Blowfish provides a good encryption rate in software and no effective cryptanalysis of it has been found to date. However, the Advanced Encryption ...

Blowfish is a symmetric-key block cipher, designed in 1993 by Bruce Schneier and included in a large number of cipher suites and encryption products. Blowfish provides a good encryption rate in software and no effective cryptanalysis of it has been found to date. However, the Advanced Encryption Standard (AES) now receives more attention.Blowfish can use huge keys and is believed secure, except with regards to its block size, which is 64 bits, just like DES and 3DES. Blowfish is efficient in software, at least on some software platforms (it uses key-dependent lookup tables, hence performance depends on how the platform handles memory and caches).

Apple has opened up its cryptographical libraries to developers in an effort to enhance the end user's security. Newly opened are the Security Framework, and Common Crypto libraries to allow developers "to help them build advanced security features," according to Apple. Security Framework provides interfaces for managing certificates, public and private keys, and trust policies. It supports the generation of cryptographically secure pseudorandom numbers. It also supports the storage of certificates and cryptographic keys in the keychain, which is a secure repository for sensitive user data. The Common Crypto library provides additional support for operations like symmetric encryption, hash-based message authentication codes, and digests.

Both Security Framework and Common Crypto rely on the corecrypto library to provide implementations of cryptographic primitives. Although corecrypto does not directly provide programming interfaces for developers and should not be used by iOS or OS X apps, the source code is now available to allow for verification of its security characteristics and correct functioning .

In here, we will use Common Crypto—a C-level API that can perform most symmetric encryption and decryption tasks like BlowFish. For using this library in swift We need to create a Bridging header file first and include this line in the header file

#import <CommonCrypto/CommonCrypto.h> and add the following functions in the project and import commonCrypto.

    func DataCryptedByBlowfish( operation: CCOperation,
                                    p: NSData,
                                  key: NSData,
                            _ options: CCOptions = CCOptions(kCCOptionPKCS7Padding),
                                 _ iv: NSData? = nil ) -> ( CCCryptorStatus, NSData ) {

        if iv != nil { assert( iv!.length == kCCBlockSizeBlowfish ) }
        var	wLength = Int( ( ( p.length + kCCBlockSizeBlowfish - 1 )
                           / kCCBlockSizeBlowfish ) * kCCBlockSizeBlowfish )
        let	v = NSMutableData( length: Int( wLength ) )!
        let	s: CCCryptorStatus = CCCrypt(operation,
                                         CCAlgorithm( kCCAlgorithmBlowfish ),
                                         options,
                                         key.bytes, Int(key.length),
                                         iv != nil ?
                                         iv!.bytes: nil,
                                         p.bytes,
                                         Int( p.length ),
                                         v.mutableBytes,
                                         wLength,
                                         &wLength)
        v.length = Int( wLength )
        return ( s, v )
    }

    func DataEncryptedByBlowfish( p: NSData,
                                key: NSData,
                           _options: CCOptions = CCOptions( kCCOptionPKCS7Padding ),
                                _iv: NSData? = nil ) -> ( CCCryptorStatus, NSData ) {
        return DataCryptedByBlowfish(CCOperation( kCCEncrypt ),
                                     p: p,
                                   key: key,
                                   _options,
                                   _iv)
    }

    func DataDecryptedByBlowfish( p: NSData,
                                key: NSData,
                           _options: CCOptions = CCOptions( kCCOptionPKCS7Padding ),
                                _iv: NSData? = nil ) -> ( CCCryptorStatus, NSData ) {
        return DataCryptedByBlowfish(CCOperation( kCCDecrypt ),
                                     p: p,
                                   key: key,
                                   _options,
                                   _iv)
    }

    func UTF8Data( p: String ) -> NSData? {
        return p.dataUsingEncoding( NSUTF8StringEncoding )
    }

    // Call this in ViewDidLoad()
    func Usage() {
        let	wKey = UTF8Data( "teststring" )!
        let	wIV = UTF8Data( "12345678" )!
        var	( s, data ) = DataEncryptedByBlowfish(UTF8Data("testmessage")!,
                                                   key: wKey,
                                              _options: CCOptions( kCCOptionPKCS7Padding ),
                                                   _iv: wIV )
        print( Int( s ) == kCCSuccess )
        print(data)
        ( s, data ) = DataDecryptedByBlowfish( data,
                                             key: wKey,
                                        _options: CCOptions( kCCOptionPKCS7Padding ),
                                             _iv: wIV )
        print( Int( s ) == kCCSuccess )
        print(data)
        print(NSString(data: data, encoding: NSUTF8StringEncoding)!)
    }

Still it is better to use one of the existing ones. Use a peer-reviewed one. It’s incredibly easy to shoot yourself in the foot with this.If professionals in the area can occasionally screw things up then the chances are, if you’re rolling your own, you’re going to make a mess of it. If the stuff you’re dealing with is very sensitive for your users, that could be a disaster.

There are IDZSwiftCommonCrypto - A Swift wrapper for Apple's CommonCrypto library or CryptoSwift- Pure Swift Implementation for Blowfish.

0