简体   繁体   中英

Swift equivalent for php's openssl_encrypt?

I am using this function to simple encrypt strings, like

    $plain_txt = "BEGIN:VCARD
    VERSION:2.1
    N:Gump;Forrest
    FN:Forrest Gump
    ORG:Bubba Gump Shrimp Co.
    TITLE:Shrimp Man
    PHOTO;GIF:http://www.example.com/dir_photos/my_photo.gif
    TEL;WORK;VOICE:(111) 555-1212
    TEL;HOME;VOICE:(404) 555-1212
    ADR;WORK:;;100 Waters Edge;Baytown;LA;30314;United States of America
    LABEL;WORK;ENCODING=QUOTED-PRINTABLE:100 Waters Edge=0D=0ABaytown, LA 30314=0D=0AUnited States of America
    ADR;HOME:;;42 Plantation St.;Baytown;LA;30314;United States of America
    LABEL;HOME;ENCODING=QUOTED-PRINTABLE:42 Plantation St.=0D=0ABaytown, LA 30314=0D=0AUnited States of America
    EMAIL;PREF;INTERNET:forrestgump@example.com
    REV:20080424T195243Z
    END:VCARD";
    echo "Plain Text = $plain_txt\n";

$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
echo "Encrypted Text = $encrypted_txt\n";

function encrypt_decrypt($action, $string) {
$output = false;

$encrypt_method = "AES-256-CBC";
$secret_key = 'This is my secret key';
$secret_iv = 'This is my secret iv';

// hash
$key = hash('sha256', $secret_key);

// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);

if( $action == 'encrypt' ) {
    $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    }
    else if( $action == 'decrypt' ){
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }

    return $output;
}

And now i like to decrypt the string in swift or any other simpler way to encrypt in PHP and decrypt in swift?

Regards

[edit 1] hmmm, apparently openssl is not ios choice

Ok i am using a quick and dirty solution and it seems to work, for now

PHP side

base64_encode($plain_txt)

And on the swift side

let decodedData = NSData(base64EncodedString: plain_txt_code, options:NSDataBase64DecodingOptions(rawValue: 0))
        let decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)

Now other scanner apps displays just base64 and not readable info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM