2

I'm trying to obtain the same encryption results (using AES 256) between PHP/mySQL and Swift.

Here is the text i'm trying to encrypt : {"email":"aze@aze.com","password":"aze"}
Here is the key : toto
I'm using the SHA1 hash of the key to encrypt : 0B9C2625DC21EF05F6AD4DDF47C5F203837AA32C

Here is my PHP code (the result is what I expect, I use a local db to perform the encryption)

$data = array();
$data['email'] = 'aze@aze.com';
$data['password'] = 'aze';

$json = json_encode($data);
$request = $db->prepare("select AES_ENCRYPT('$json', SHA1('toto')) as data from dual");
$request->execute();
$request->setFetchMode(PDO::FETCH_ASSOC);

$encodedResult = $request->fetchAll();
$encodedResult = $encodedResult[0]['data'];

$base64Result = base64_encode($encodedResult));

Encoded result is ¤]¼–áú£?îfÞð"2Á«­¯ä%s7Ûš>½qé}‘(J µƒ–"³}vÃë
Base64 result is pF28A5bh+qOdP+5mHN7wIjLBBKutr+Qlczfbmj69cel9kRYoShcgtYOWIrN9dsPr

How can I obtain the same result in Swift or Objective-C ? I tried different libraries such as CryptoSwift / CocoaSecurity, but the result is always different.
It seems that MySQL uses 0 padding, which I can't get to work on iOS.

Edit : To be clear I need to implement 0 padding on iOS side to obtain the same result as MySQL, and not PKCS7 on PHP/MySQL side.

gobtronic
  • 331
  • 1
  • 2
  • 12
  • 1
    You're using a database connection solely for executing `AES_ENCRYPT`...!? While being open to SQL injection?! You are aware that you can write equivalent encryption code purely in PHP without the needless overhead of involving MySQL?! – deceze Aug 24 '15 at 14:53
  • That is not the point, I'm not using this code or PHP in production. I just want to obtain the same result. – gobtronic Aug 24 '15 at 14:56
  • possible duplicate of [Different results in AES256 encryption in Swift (iOS) and PHP](http://stackoverflow.com/questions/25980212/different-results-in-aes256-encryption-in-swift-ios-and-php) – Eric Aya Aug 24 '15 at 15:06

1 Answers1

0

With CryptoSwift you can easily apply custom padding

public struct ZeroPadding: Padding {
    func add(data: [UInt8], blockSize:Int) -> [UInt8] {
        // Padding logic here
    }

    func remove(data: [UInt8], blockSize:Int?) -> [UInt8] {
        // Padding logic here
    }
}

and pass it as parameter to encrypt()

let encrypted = AES(key: key, iv: iv, blockMode: .CBC)?.encrypt(message, padding: ZeroPadding())
Marcin
  • 3,694
  • 5
  • 32
  • 52