What would be an equivalent for:
hash_hmac('sha256', 'data', 'key')
if I were using openssl_*?
openssl_digest does not take $key parameter.
This function uses the openssl_* extension to hash the data and the key:
Code
function openssl_hmac($algo, $data, $key, $raw_output = false)
{
$algo = strtolower($algo);
$pack = 'H' . strlen(openssl_digest('test', $algo));
$size = 64;
$opad = str_repeat(chr(0x5C), $size);
$ipad = str_repeat(chr(0x36), $size);
if (strlen($key) > $size) {
$key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
} else {
$key = str_pad($key, $size, chr(0x00));
}
for ($i = 0; $i < strlen($key) - 1; $i++) {
$opad[$i] = $opad[$i] ^ $key[$i];
$ipad[$i] = $ipad[$i] ^ $key[$i];
}
$output = openssl_digest($opad . pack($pack, openssl_digest($ipad . $data, $algo)), $algo);
return ($raw_output) ? pack($pack, $output) : $output;
}
Usage
echo openssl_hmac('sha256', 'data', 'key', false);
Result:
5031fe3d989c6d1537a013fa6e739da23463fdaec3b70137d828e36ace221bd0
The result is the same as when using the hash_hmac function:
echo hash_hmac('sha256', 'data', 'key');
Result:
5031fe3d989c6d1537a013fa6e739da23463fdaec3b70137d828e36ace221bd0
Related
I'm trying to make a program where people can chat and I want to encrypt the messages that are being sent. I have 2 scripts for this, one is sendtext.php and another getchat.php.
So my question is how can I encrypt the text that's being sent in one file and then decrypt the messages that will be sent back which is in another file.
So far I have the encryption working but I dont know how to decrypt in the other file.
Also if you know a more secure way of doing this it would be appreciated.
sendtext.php
$username = $_POST["name"];
$text = $_POST["message"];
$key = openssl_random_pseudo_bytes(32, $cstrong);
$cipher = "aes-128-gcm";
if (in_array($cipher, openssl_get_cipher_methods()))
{
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($text, $cipher, $key, $options=0, $iv, $tag);
echo "Encrytped: " . $ciphertext;
//store $cipher, $iv, and $tag for decryption later
//$original_text = openssl_decrypt($ciphertext, $cipher, $key, $options=0, $iv, $tag);
//echo $original_text."\n";
}
//Add text to the table
$inserttextquery = "INSERT INTO ".$username." (username, message)
VALUES ('$username', '$ciphertext');";
mysqli_query($con, $inserttextquery) or die("#: send text failed");
getchat.php
$username = $_POST["name"];
$sql = "SELECT username, message FROM ".$username."";
$result = $con->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["username"] . "\t" . $row["message"] . "\t";
}
}
I wrote this encryption/decryption class awhile ago:
<?php
class Cryptography
{
private static $secret_key = 'gsdgsg423b523b5432bjbjm24vbjn2hv';
const CIPHER_16 = 'AES-128-CBC';
const CIPHER_32 = 'AES-256-CBC';
public static function encrypt($str, $cl = 32)
{
return static::encyptedDecypted('encrypt', $str, $cl);
}
public static function decrypt($str, $cl = 32)
{
return static::encyptedDecypted('decrypt', $str, $cl);
}
public static function encyptedDecypted($action, $str, $cl)
{
$cl = (int) $cl;
if ($cl === 16) {
$cipher = static::CIPHER_16;
$length = 16;
} elseif ($cl === 32) {
$cipher = static::CIPHER_32;
$length = 32;
} else {
throw new Exception('Error Processing Request', 1);
}
$iv = $iv = substr(hash('sha256', static:: $secret_key), 0, 16);
$key = hash('sha512', static::$secret_key);
if ($action == 'encrypt') {
$output = openssl_encrypt($str, $cipher, $key, 0, $iv);
$output = base64_encode($output);
$output = static::securesalts($length).$output.static::securesalts($length);
} elseif ($action == 'decrypt') {
$str = $text = substr($str, $length, -$length);
$output = openssl_decrypt(base64_decode($str), $cipher, $key, 0, $iv);
}
return $output;
}
private static function securesalts($length)
{
if (is_int($length) && $length >= 5) {
$chars = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
$stringlength = count($chars); //Used Count because its array now
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $chars[rand(0, $stringlength - 1)];
}
return $randomString;
} else {
return false;
}
}
}
Use it like this:
$str = "Simple String";
//for encryption
$encrypted = Cryptography::encrypt($str);
//for decryption
$decrypted = Cryptography::decrypt($encrypted);
Don't forget to change the $secret_key ;)
This is my C# code but I want same encrypted string in PHP. Can you please help me in any way.
var token ="MqsXexqpYRUNAHR_lHkPRic1g1BYhH6bFNVPagEkuaL8Mf80l_tOirhThQYIbfWYErgu4bDwl-7brVhXTWnJNQ2";
var id = "bob#company.com";
var ssokey = "7MpszrQpO95p7H";
string idAndKey = id + ssokey;
var salt = HttpServerUtility.UrlTokenDecode(token);
var pbkdf2 = new Rfc2898DeriveBytes(idAndKey, salt) {IterationCount = 1000};
var key = HttpServerUtility.UrlTokenEncode(pbkdf2.GetBytes(24));
//key = aE1k9-djZ66WbUATqdHbWyJzskMI5ABS0;
My PHP code is:
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'),strlen($data) % 4, '=', STR_PAD_RIGHT));
}
$token = "MqsXexqpYRUNAHR_lHkPRic1g1BYhH6bFNVPagEkuaL8Mf80l_tOirhThQYIbfWYErgu4bDwl-7brVhXTWnJNQ2";
$id = "bob#company.com";
$ssokey = "7MpszrQpO95p7H";
$idAndKey = $id.$ssokey;
$salt = base64_decode(base64url_decode($token));
$pbkdf2 = openssl_pbkdf2($idAndKey,$salt,20,1000);
$key = base64url_encode(base64_encode($pbkdf2));
//should produce key = aE1k9-djZ66WbUATqdHbWyJzskMI5ABS0
echo "key = ".$key; exit;
It should give aE1k9-djZ66WbUATqdHbWyJzskMI5ABS0 but is produced differently.
Any help is appreciated.
$idandKey = "bob#company.com" . "7MpszrQpO95p7H";
$salt = convertFromUrlTokenFormat("MqsXexqpYRUNAHR_lHkPRic1g1BYhH6bFNVPagEkuaL8Mf80l_tOirhThQYIbfWYErgu4bDwl-7brVhXTWnJNQ2");
$hash = hash_pbkdf2("sha1", $idandKey, base64_decode($salt), 1000, 24, true);
$key = convertToUrlTokenFormat(base64_encode($hash));
// key = “aE1k9-djZ66WbUATqdHbWyJzskMI5ABS0”;
function convertToUrlTokenFormat($val){
$padding = substr_count($val, '=');
$val = str_replace('=', '', $val);
$val .= $padding;
$val = str_replace('+', '-', str_replace('/', '_', $val));
return $val;
}
function convertFromUrlTokenFormat($val){
$val = str_replace('-', '+', str_replace('_', '/', $val));
$lastCharacter = substr($val, -1);
$val = substr($val, 0, -1);
switch($lastCharacter){
case 1:
$val = $val . "=";
break;
case 2:
$val = $val . "==";
break;
}
return $val;
}
I have a big problem with hash_hmac
function
function hmac($key, $data){
$blocksize = 64;
$hashfunc = 'sha1';
if (strlen($key) > $blocksize)
$key = pack('H*', $hashfunc($key));
$key = str_pad($key, $blocksize, chr(0x00));
$ipad = str_repeat(chr(0x36), $blocksize);
$opad = str_repeat(chr(0x5c), $blocksize);
$hmac = pack('H*', $hashfunc(($key ^ $opad) . pack('H*', $hashfunc(($key ^ $ipad) . $data))));
return bin2hex($hmac);
}
example is:
<?php
echo hmac('111111', '222222');//=1558ab6c5ab2b0d1cd129b9ad11527cf33486705
but my
$jeden = 111111;
$dwa =222222;
$hashWiadomosci = hash_hmac('sha1', $jeden, $dwa);
is: 22f91d281349bb3081d3cec9f906572eec5c55b2
how i do wrong?
You have your input variables in the wrong order. If you look at the example from the comment you got this from; you can see that it is hmacsha1($key, $data) and not hmacsha1($data, $key) like you are using it and how hash_hmac($algorithm, $data, $key) works.
echo hash_hmac('sha1', '111111', '222222'); // 22f91d2813...
echo hmacsha1('111111', '222222'); // 1558ab6c5a...
echo hash_hmac('sha1', '111111', '222222'); // 22f91d2813...
echo hmacsha1('222222', '111111'); // 22f91d2813...
I find theese php codes here, but codes aren't working correctly. it seems that the if(isset($words[$word])) doesn't go through as I always get an empty results array
$boggle = "fxie
amlo
ewbx
astu";
$alphabet = str_split(str_replace(array("\n", " ", "\r"), "", strtolower($boggle)));
$rows = array_map('trim', explode("\n", $boggle));
$dictionary = file("C:/dict.txt");
$prefixes = array(''=>'');
$words = array();
$regex = '/[' . implode('', $alphabet) . ']{3,}$/S';
foreach($dictionary as $k=>$value) {
$value = trim(strtolower($value));
$length = strlen($value);
if(preg_match($regex, $value)) {
for($x = 0; $x < $length; $x++) {
$letter = substr($value, 0, $x+1);
if($letter == $value) {
$words[$value] = 1;
} else {
$prefixes[$letter] = 1;
}
}
}
}
$graph = array();
$chardict = array();
$positions = array();
$c = count($rows);
for($i = 0; $i < $c; $i++) {
$l = strlen($rows[$i]);
for($j = 0; $j < $l; $j++) {
$chardict[$i.','.$j] = $rows[$i][$j];
$children = array();
$pos = array(-1,0,1);
foreach($pos as $z) {
$xCoord = $z + $i;
if($xCoord < 0 || $xCoord >= count($rows)) {
continue;
}
$len = strlen($rows[0]);
foreach($pos as $w) {
$yCoord = $j + $w;
if(($yCoord < 0 || $yCoord >= $len) || ($z == 0 && $w == 0)) {
continue;
}
$children[] = array($xCoord, $yCoord);
}
}
$graph['None'][] = array($i, $j);
$graph[$i.','.$j] = $children;
}
}
function to_word($chardict, $prefix) {
$word = array();
foreach($prefix as $v) {
$word[] = $chardict[$v[0].','.$v[1]];
}
return implode("", $word);
}
function find_words($graph, $chardict, $position, $prefix, $prefixes, &$results, $words) {
$word = to_word($chardict, $prefix);
if(!isset($prefixes[$word])) return false;
**if(isset($words[$word])) {
$results[] = $word;
}**
foreach($graph[$position] as $child) {
if(!in_array($child, $prefix)) {
$newprefix = $prefix;
$newprefix[] = $child;
find_words($graph, $chardict, $child[0].','.$child[1], $newprefix, $prefixes, $results, $words);
}
}
}
$solution = array();
find_words($graph, $chardict, 'None', array(), $prefixes, $solution);
print_r($solution);
When you call find_words() at the end, you are only passing 6 parameters
find_words($graph, $chardict, 'None', array(), $prefixes, $solution);
The variable $words, is the 7th parameter in your definition of find_words()
function find_words($graph, $chardict, $position, $prefix, $prefixes, &$results, $words) {
Hence, $words will always be empty, and isset($words[$word]) will always be false
I am trying to get email contact from hotmail with php or javascript.
I have read that windows live api return only hash of the email contact, and it is proved by the code example:
http://isdk.dev.live.com/ISDK.aspx
But some web site like facebook can retrieve the plaintext of email contact from hotmail. How it is possible?
Thanks a lot.
Simply change the scope to:
wl.basic,wl.contacts_emails
You can test this code (dont forget to [SECRET API KEY] with your api key) :
<?php
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
function unfucked_base_convert ($numstring, $frombase, $tobase) {
$chars = "0123456789abcdefghijklmnopqrstuvwxyz";
$tostring = substr($chars, 0, $tobase);
$length = strlen($numstring);
$result = '';
for ($i = 0; $i < $length; $i++) {
$number[$i] = strpos($chars, $numstring{$i});
}
do {
$divide = 0;
$newlen = 0;
for ($i = 0; $i < $length; $i++) {
$divide = $divide * $frombase + $number[$i];
if ($divide >= $tobase) {
$number[$newlen++] = (int)($divide / $tobase);
$divide = $divide % $tobase;
} elseif ($newlen > 0) {
$number[$newlen++] = 0;
}
}
$length = $newlen;
$result = $tostring{$divide} . $result;
}
while ($newlen != 0);
return $result;
}
function hexaTo64SignedDecimal($hexa) {
$bin = unfucked_base_convert($hexa, 16, 2);
if(64 === strlen($bin) and 1 == $bin[0]) {
$inv_bin = strtr($bin, '01', '10');
$i = 63;
while (0 !== $i) {
if(0 == $inv_bin[$i]) {
$inv_bin[$i] = 1;
$i = 0;
}
else {
$inv_bin[$i] = 0;
$i–;
}
}
return '-'.unfucked_base_convert($inv_bin, 2, 10);
}
else {
return unfucked_base_convert($hexa, 16, 10);
}
}
function email2nickname($email) {
$output = str_replace(array('.', '-', '_', ',', ':'), ' ', substr($email, 0, strpos($email, '#')));
$output = str_replace(array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), '', $output);
$output = ucwords($output);
return $output;
}
function grabLiveContacts($token) {
if(!empty($token)) {
$HOTMAIL_CLIENT_SECRET='[SECRET API KEY]';
parse_str(urldecode($token), $parsedToken);
$token = base64_decode($parsedToken['delt']);
$cryptkey = substr( hash('sha256', 'ENCRYPTION' . $HOTMAIL_CLIENT_SECRET, true), 0, 16);
parse_str(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $cryptkey, substr($token, 16), MCRYPT_MODE_CBC, substr($token, 0, 16)),$result);
$intlid = hexaTo64SignedDecimal($parsedToken['lid']);
$url = 'https://livecontacts.services.live.com/users/#C#'.$intlid.'/rest/livecontacts';
$headers = array(
'Authorization: DelegatedToken dt="'.$parsedToken['delt'].'"'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
$xml = new SimpleXMLElement($data);
$grab = array();
$grab['user'] = array(
'name'=>trim(strval($xml->Owner->Profiles->Personal->DisplayName)),
'email'=>trim(strval($xml->Owner->WindowsLiveID)), 'token'=>$token
);
$grab['contacts'] = array();
foreach ($xml->Contacts->Contact as $entry) {
$name = trim(strval($entry->Profiles->Personal->DisplayName));
if (isset($entry->Emails->Email->Address)){
$email = trim(strval($entry->Emails->Email->Address));
if(!empty($email)) {
if(empty($name)) {
$name = trim(strval($entry->Profiles->Personal->FirstName));
$name .= ' '.trim(strval($entry->Profiles->Personal->LastName));
$name = trim($name);
}
if(empty($name)) {
$name = trim(strval($entry->Profiles->Personal->NickName));
}
if(empty($name) or isEmail($name)) {
$name = email2nickname($email);
}
$grab['contacts'][] = array('name'=>$name, 'email'=>$email);
}
}
}
return $grab;
}
else return false;
}
if(isset($_POST['ConsentToken'])) {
$grab = grabLiveContacts($_POST['ConsentToken']);
foreach ($grab['contacts'] as $contact){
if (isset($contact['email'])){
echo($contact['email']."</br>");
}
}
}
?>