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.
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!
Related
I'm trying to encode a message in flutter and to verify it with some php code, but somehow there are some differences in the hmac encoding. The header and payload values are the same in both cases. But somehow there are some differences between the resulting values.
Any help would be very helpful, I'm stuck on this for some days now.
$base64UrlHeader = 'header';
$base64UrlPayload = 'payload';
$secret = 'secret';
$signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, $secret, true); // 9b491a7aa29955d9d67e302965665ba0cfa4306c00470f8946eb6aa67f676595
$base64UrlSignature = base64UrlEncode($signature); // sYql52zk6tqYeGSUsDv_219UtgpK3c8-TMuko4n_L5Q
function base64UrlEncode($text) {
return str_replace(
['+', '/', '='],
['-', '_', ''],
base64_encode($text)
);
}
And this is my dart code:
// This values are obtained by using the _base64UrlEncode method from below,
// I just wrote the values directly here not to clutter with code
var base64UrlHeader = 'header';
var base64UrlPayload = 'payload';
/// SIGNATURE
var secret = utf8.encode('secret');
var message = utf8.encode(base64UrlHeader + '.' + base64UrlPayload);
var hmac = new Hmac(sha256, secret);
var digest = hmac.convert(message); // b18aa5e76ce4eada98786494b03bffdb5f54b60a4addcf3e4ccba4a389ff2f94
var signature = _base64UrlEncode(digest.toString()) // YjE4YWE1ZTc2Y2U0ZWFkYTk4Nzg2NDk0YjAzYmZmZGI1ZjU0YjYwYTRhZGRjZjNlNGNjYmE0YTM4OWZmMmY5NA
// This method is used to obtain the header, payload and signature
static String _base64UrlEncode(String text) {
Codec<String, String> stringToBase64Url = utf8.fuse(base64url);
return stringToBase64Url
.encode(text)
.replaceAll('=', '')
.replaceAll('+', '-')
.replaceAll('/', '_');
}
Both the header and payload are obtained from the same json object,
I'm trying to get this working in flutter and i cant get the same outcome.
My php code prints a diffrent hash then my flutter code. Is it posible to do this in a flutter app?
i have tried to achieve this by running this flutter code. But after 5 hours of reading i gave up and created a stack overflow account.
import 'package:crypto/crypto.dart';
import 'dart:convert'; // for the utf8.encode method
import 'package:http/http.dart' as http;
void main() {
var api = 'https://app.repricer.nl';
var endpoint = '/api/v1/channels/all.json';
var method = 'GET';
var public_key = '';
var private_key = '';
var data = '';
var ms = (new DateTime.now()).millisecondsSinceEpoch;
var timestamp = ms / 1000;
var hash_string = public_key + '|' + method + '|' + endpoint + '|' + data + '|' + timestamp.toString();
var key = utf8.encode(private_key);
var bytes = utf8.encode(hash_string);
var hmacSha256 = new Hmac(sha512, key); // HMAC-SHA256
var digest = hmacSha256.convert(bytes);
print(digest);
}
This is the PHP code that i want to convert to flutter:
$api = 'https://app.repricer.nl';
$endpoint = '/api/v1/channels/all.json';
$method = 'GET';
$public_key = '';
$private_key = '';
// Generate the CURL headers to authenticate our request
$headers = generateHash($public_key, $private_key, $method, $endpoint, $data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$api.$endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
function generateHash($public_key, $private_key, $method, $endpoint, $data)
{
$timestamp = date("U");
$hash_string = array($public_key,$method,$endpoint,$data,$timestamp);
$hash = hash_hmac('sha512',implode('|',$hash_string),$private_key);
print ($hash);
return array('X-Auth: '.$public_key, 'X-Hash: '.$hash, 'X-Date: '.$timestamp);
}
I expect the output is the same exept from the timestamp. But i ran it in the same second and it are 2 completly diffrent outcomes.
Your code is correct.
Small fix is just replacing:
ms / 1000 to (ms / 1000).toInt()
I don't see other flaw in Your code.
I've came to that answer after doing test run with constant timestamp parameter: 1572731120
PHP:
$timestamp = 1572731120; //date("U");
$hash_string = array($public_key,$method,$endpoint,$data,$timestamp);
$hash = hash_hmac('sha512',implode('|',$hash_string),$private_key);
Dart
var ms = (new DateTime.now()).millisecondsSinceEpoch;
var timestamp = 1572731120;//(ms / 1000).toInt();
var hash_string = public_key + '|' + method + '|' + endpoint + '|' + data + '|' + timestamp.toString();
var key = utf8.encode(private_key);
var bytes = utf8.encode(hash_string);
var hmacSha256 = new Hmac(sha512, key); // HMAC-SHA256
var digest = hmacSha256.convert(bytes);
which proves that results are equal:
I am trying to follow part of a tutorial for an API written in PHP. They show the following example:
$public = 'JkAFq7M47kLN0xVD';
$private = 'E6X9FyZvMFeJbqtq.IwjlTuR.MKDoicB';
$url = 'https://pterodactyl.local/api/admin/users';
$body = '';
$hmac = hash_hmac('sha256', $url . $body, $private, true);
return $public . '.' . base64_encode($hmac);
// Should return the string below:
//
// JkAFq7M47kLN0xVD.wgIxj+V8RHgIetcQg2lRM0PRSH/y5M21cPz9zVhfFaQ=
But my method doesn't return the proper value. Instead it returns the following:
JkAFq7M47kLN0xVD./RKZS3U2FKfEt7/tEks4vWwyS+89lL+k8aEGO8NJWuo=
Here is my code:
hmac = crypto.createHmac('sha256', private_key);
hmac.write(url+body);
hmac.end();
hash = hmac.read().toString('base64');
console.log(hash);
EDIT: I think the example they provided was invalid because as everyone is saying my code is almost identical and the PHP code outputs a different value then it said it should in the documentation.
ok so, i used this tool writephponline to run this php code:
$public = 'JkAFq7M47kLN0xVD';
$private = 'E6X9FyZvMFeJbqtq.IwjlTuR.MKDoicB';
$url = 'https://pterodactyl.local/api/admin/users';
$body = '';
$hmac = hash_hmac('sha256', $url . $body, $private, true);
echo $public . '.' . base64_encode($hmac);
and returns:
JkAFq7M47kLN0xVD./RKZS3U2FKfEt7/tEks4vWwyS+89lL+k8aEGO8NJWuo=
So i used that as a parameter, then i made a little nodejs script:
var crypto = require('crypto');
var public = 'JkAFq7M47kLN0xVD';
var private = 'E6X9FyZvMFeJbqtq.IwjlTuR.MKDoicB';
var url = 'https://pterodactyl.local/api/admin/users';
var body = '';
var hmac = crypto.createHmac('sha256', private).update(url+body).digest('base64');
console.log(public + '.' + hmac);
and returns:
JkAFq7M47kLN0xVD./RKZS3U2FKfEt7/tEks4vWwyS+89lL+k8aEGO8NJWuo=
Hope it helps.
I am prefer use crypto-js library of crypto standards. This library is keep maintaining.
const crypto = require('crypto-js')
const public = 'JkAFq7M47kLN0xVD'
const private = 'E6X9FyZvMFeJbqtq.IwjlTuR.MKDoicB'
const url = 'https://pterodactyl.local/api/admin/users'
const body = ''
const hmac = crypto.HmacSHA256(url + body, private).toString(crypto.enc.Base64)
console.log(public + '.' + hmac)
// Print value:
// JkAFq7M47kLN0xVD./RKZS3U2FKfEt7/tEks4vWwyS+89lL+k8aEGO8NJWuo=
everyone!
I have some PHP code to sign some text and it works fine. I need to have equivalent of this code on actionscript 3. I need your help.
$privateKeyPath = "private.key";
$message = "hello";
$privateKey = file_get_contents($privateKeyPath);
openssl_sign($message, $signature, $privateKey);
echo base64_encode($signature);
In AS3 I using as3crypto library to make sign:
private function readPrivateKey():String {
var f:File = new File("/Users/ivan/Desktop/private.key");
var fs:FileStream = new FileStream();
fs.open(f,FileMode.READ);
var key:String = fs.readUTFBytes(fs.bytesAvailable);
fs.close();
return key;
}
private function getSign():void {
var message:String = "hello";
var privateKey:String = readPrivateKey();
var srcBA:ByteArray = new ByteArray();
var resultBA:ByteArray = new ByteArray();
var rsaKey:RSAKey;
var base64encoder:Base64Encoder = new Base64Encoder();
srcBA.writeUTFBytes(message);
rsaKey = PEM.readRSAPrivateKey(privateKey);
rsaKey.sign(srcBA, resultBA, srcBA.length);
b64encoder.encodeBytes(resultBA);
trace(b64encoder.toString());
}
I have same private key file. I expect that the output values are equals. But these values are different =(
What am I doing wrong?
UPDATE: I tried to verify my encoded base64 string using public key and verify method - everything is ok inside Actionscript.
Example:
var text:String = "hello";
var srcBA:ByteArray;
var desBA:ByteArray;
var rsaKey:RSAKey;
var encodedB64:String;
// ENCODING
srcBA = new ByteArray();
srcBA.writeUTFBytes(text);
desBA = new ByteArray();
rsaKey = PEM.readRSAPrivateKey( readPrivateKey() );
rsaKey.sign(srcBA, desBA, srcBA.length);
encodedB64 = Base64.encodeByteArray(desBA);
trace("Original: " + text);
trace("Encoded: " + encodedB64 );
// DECODING
var srcBA2:ByteArray = new ByteArray();
var desBA2:ByteArray = new ByteArray();
var rsaKey2:RSAKey = PEM.readRSAPublicKey( readPublicKey() );
srcBA2 = Base64.decodeToByteArray( encodedB64 );
rsaKey2.verify(srcBA2, desBA2, srcBA2.length);
trace("Decoded: " + desBA2.toString() );
My original text and decoded value are equals. So, I conclude that AS3 signing methods are different than PHP.
Is anyone have idea to make it equals?
Thanks.
Maybe it's late answer, but anyway...
AS3 works fine in your second code, PHP needs some tweaks, like this:
$privateKeyPath = "private.key";
$message = "hello";
$privateKey = openssl_pkey_get_private(file_get_contents($privateKeyPath));
openssl_private_encrypt($message, $signature, $privateKey);
echo base64_encode($signature);
I just checked with key genereted on this site:
http://www.selfsignedcertificate.com/ and everything works fine, I'm getting similar results in both PHP and AS3 versions.
I converting a swf project to php, I'm not good with actionscript much so I need help to convert functions Hex.toArray, Hex.fromString, Base64.encodeByteArray in actionscript3 to php.
ActionScript
public function spawn(query_str:String, key:String, token:String = "") : String{
var tmp1:* = key + "&" + token;
var tmp2:* = Crypto.getHMAC("sha1");
var tmp3:* = Hex.toArray(Hex.fromString(tmp1));
var tmp4:* = Hex.toArray(Hex.fromString(query_str));
var tmp5:* = tmp2.compute(tmp3, tmp4);
return Base64.encodeByteArray(tmp5);
}
This is PHP function I converted, but results of two functions are different
function spawn($query_str, $key, $token = ''){
$tmp1 = $key . "&" . $token;
$tmp3 = pack("H*" , bin2hex($tmp1));
$tmp4 = pack("H*" , bin2hex($query_str));
$tmp5 = hash_hmac('sha1', $tmp4, $tmp3);
return base64_encode($tmp5);
}
You can use bin2hex in PHP, and pack("H*", ...) in lieu of hex2bin. The primarily used base64 functions in PHP are base64_encode and base64_decode.
Arrays are seldomly used for data representation; binary data is generally kept in strings in PHP. But if really needed $array = array_map("ord", str_split($string)); would do.