akiratzpt / as3crypto

Automatically exported from code.google.com/p/as3crypto
0 stars 0 forks source link

RSA sign function problem #63

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
I'm working on rsa sign function for generate 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;
}

What is the expected output? What do you see instead?
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. Any idea?
Please help me!

Thanks in advice

Original issue reported on code.google.com by nikola....@gmail.com on 14 Jun 2011 at 2:23