Search code examples
phpapache-flexencryptionrsaas3crypto

RSA sign function problem


I'm working on an RSA sign() function for generating a signed URL for private streaming. I was testing on PHP code, but I want to re-code that in Flex. Here is the part of PHP code:

function getCannedPolicy($resource, $expires, $key, $privatekeyfile){
         $priv_key = file_get_contents($privatekeyfile);
         $pkeyid = openssl_get_privatekey($priv_key);
         $policy_str = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';
         $policy_str = trim( preg_replace( '/\s+/', '', $policy_str ) );
         $res = openssl_sign($policy_str, $signature, $pkeyid, OPENSSL_ALGO_SHA1);
         $signature_base64 = (base64_encode($signature));
         $repl = array('+' => '-','=' => '_','/' => '~');
         $signature_base64 = strtr($signature_base64,$repl);
         $url = $resource . '?Expires='.$expires. '&Signature=' . $signature_base64 . '&Key-Pair-Id='. $key;

         return $url;
}

I write the same function in Flex. Here is the code:

private function getCannedPolicy(resource:String, expires:uint, key:String, privatekey:String):String{          
    var unsigned:String = '{"Statement":[{"Resource":"' +resource+ '","Condition":{"DateLessThan":{"AWS:EpochTime":' +expires+ '}}}]}';
    var signed:String = '';
    var signature:String = '';
    var regex:RegExp = /\s+/g;          
    unsigned = unsigned.replace(regex,'');
    var src:ByteArray = new ByteArray();            
    src.writeUTFBytes(unsigned);            
    var dst:ByteArray = new ByteArray();            
    var hash:SHA1 = new SHA1();
    src = hash.hash(src);                       
    var rsa:RSAKey = PEM.readRSAPrivateKey(privatekey);
    trace(rsa.dump());
    rsa.sign(src, dst, src.length);
    dst.position = 0;           
    signature = Base64.encodeByteArray(dst);                            
    signature = signature.split("+").join("-");
    signature = signature.split("=").join("_");
    signature = signature.split("\/").join("~");
    signed = resource+'?Expires=' +expires+ '&Signature=' +signature+ '&Key-Pair-Id=' +key; 

    return signed;
}

The outputs from the two functions (the PHP and the Flex) are the same format. But, when I'm using the signed URL from the Flex function, the stream not work.

The alternative I'm using for openssl_sign() php function is sign() function from as3crypto library. Maybe here is the problem? Maybe the encryption is different.


Solution

  • Unfortunately, the as3crypto's RSAKey.sign() is not the same function as php's openssl_sign(). Their outputs are different signatures. For that reason I decide to call remote php function to generated my signature. It works now!