(Please note that the function I reference from the provided answer didn't work so I want to modify it to make it work or please provide a suitable solution to AES encryption in VueJS and decryption in PHP (or Laravel))
I have a password will be sent to Laravel API so I managed to encrypt and base64 it then send it to Laravel API. Here's the original encryption
And here's the encryption and encoding
var encryptedPassword = CryptoJS.AES.encrypt("123456", "Secret Passphrase");
const replacerFunc = () => {
const visited = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (visited.has(value)) {
return;
}
visited.add(value);
}
return value;
};
};
let jsonString = JSON.stringify(encryptedPassword, replacerFunc());
let bs46encoded = btoa(unescape(encodeURIComponent(JSON.stringify(jsonString, replacerFunc()))))
I get this result
IntcIiRzdXBlclwiOntcIiRzdXBlclwiOnt9fSxcImNpcGhlcnRleHRcIjp7XCJ3b3Jkc1wiOlsxODQ4NTYxMTAzLDE1MjkyNDgyMTUsLTEwODg3MTk1MDEsLTEyNjAyOTYzNjJdLFwic2lnQnl0ZXNcIjoxNn0sXCJrZXlcIjp7XCIkc3VwZXJcIjp7fSxcIndvcmRzXCI6Wy0yODA5NjkxMjcsNzAzNjYxOTM0LDE1Mjg5OTYxNDEsLTEwOTU5OTQ2MDYsLTY4OTMyOTM1NiwtNDQ1MDc3MjE3LC0yMDM4MDY1MTUxLC0xNzI0MjIzMzE4LC0xNTk1Nzk5MDI5LDgxOTY1NjMwMSwtMTQzNTIxMDg2NCwxODkwMDcyNTc5XSxcInNpZ0J5dGVzXCI6MzJ9LFwiaXZcIjp7XCJ3b3Jkc1wiOlstMTU5NTc5OTAyOSw4MTk2NTYzMDEsLTE0MzUyMTA4NjQsMTg5MDA3MjU3OV0sXCJzaWdCeXRlc1wiOjE2fSxcImFsZ29yaXRobVwiOntcImtleVNpemVcIjo4LFwiJHN1cGVyXCI6e1wiY2ZnXCI6e1wibW9kZVwiOntcIiRzdXBlclwiOnt9LFwiRW5jcnlwdG9yXCI6e30sXCJEZWNyeXB0b3JcIjp7fX0sXCJwYWRkaW5nXCI6e30sXCIkc3VwZXJcIjp7fX0sXCJibG9ja1NpemVcIjo0LFwiJHN1cGVyXCI6e1wia2V5U2l6ZVwiOjQsXCJpdlNpemVcIjo0LFwiX0VOQ19YRk9STV9NT0RFXCI6MSxcIl9ERUNfWEZPUk1fTU9ERVwiOjIsXCIkc3VwZXJcIjp7XCJfbWluQnVmZmVyU2l6ZVwiOjB9fX19LFwiYmxvY2tTaXplXCI6NCxcImZvcm1hdHRlclwiOnt9LFwic2FsdFwiOntcIndvcmRzXCI6WzE5NDk1NjcxNjIsMjExODc0MjAyOF0sXCJzaWdCeXRlc1wiOjh9fSI=
In laravel
$objString = base64_decode($ecodedString);
And I get
"{\"$super\":{\"$super\":{}},\"ciphertext\":{\"words\":[-1208966431,415513002,-380428285,-1848403568],\"sigBytes\":16},\
"key\":{\"$super\":{},\"words\":[1997420112,-1528658502,-601329304,170123410,85401029,1271916135,-1899682466,856024313,-1926693888,505524620,1922976396,79922502],\"sigBytes\":32},
\"iv\":{\"words\":[-1926693888,505524620,1922976396,79922502],\"sigBytes\":16},\"algorithm\":{\"keySize\":8,\"$super\":{\"cfg\":{\"mode\":{\"$super\":{},\"Encryptor\":{},\"Decryptor\":{}},\"padding\":{},\"$super\":{}},\"blockSize\":4,\"$super\":{\"keySize\":4,\"ivSize\":4,\"_ENC_XFORM_MODE\":1,\"_DEC_XFORM_MODE\":2,\"$super\":{\"_minBufferSize\":0}}}},\"blockSize\":4,\"formatter\":{},
\"salt\":{\"words\":[3335652791,3193595722],\"sigBytes\":8}}"
Then
$this->cryptoJsAesDecrypt("Secret Passphrase", $objString);
public function cryptoJsAesDecrypt($passphrase, $jsonString){
$jsondata = json_decode($jsonString, true);
Log::alert("jsondata");
Log::alert($jsondata);
$salt = hex2bin($jsondata["salt"]);
$ct = base64_decode($jsondata["ct"]);
$iv = hex2bin($jsondata["iv"]);
$concatedPassphrase = $passphrase.$salt;
$md5 = array();
$md5[0] = md5($concatedPassphrase, true);
$result = $md5[0];
for ($i = 1; $i < 3; $i++) {
$md5[$i] = md5($md5[$i - 1].$concatedPassphrase, true);
$result .= $md5[$i];
}
$key = substr($result, 0, 32);
$data = openssl_decrypt($ct, 'aes-256-cbc', $key, true, $iv);
Log::alert("data");
Log::alert($data);
return $data;
}
$jsondata returns
{"$super":{"$super":{}},"ciphertext":{"words":[-1208966431,415513002,-380428285,-1848403568],"sigBytes":16},
"key":{"$super":{},"words":[1997420112,-1528658502,-601329304,170123410,85401029,1271916135,-1899682466,856024313,-1926693888,505524620,1922976396,79922502],"sigBytes":32},
"iv":{"words":[-1926693888,505524620,1922976396,79922502],"sigBytes":16},"algorithm":{"keySize":8,"$super":{"cfg":{"mode":{"$super":{},"Encryptor":{},"Decryptor":{}},"padding":{},"$super":{}},"blockSize":4,"$super":{"keySize":4,"ivSize":4,"_ENC_XFORM_MODE":1,"_DEC_XFORM_MODE":2,"$super":{"_minBufferSize":0}}}},"blockSize":4,"formatter":{},
"salt":{"words":[3335652791,3193595722],"sigBytes":8}}
But can't get other variables correctly to decrypt this encryption and find the original plain text. How can I edit this function to make it work?
I try to clone this answer Encryption in JavaScript and decryption with PHP
Related
I been working on this for days.
Our backend have a signature checking which is done using PHP:
private $HMAC_ALGO = 'md5';
public function decodeAndValidateMessage($data,$signature,$secretkey) {
if (!is_string($data)) {
throw new InvalidRequestException($data);
}
$decodedData = base64_decode($data);
// if not json returned the throw exception...
$jsonDecoded = json_decode($decodedData,true);
if (!$jsonDecoded) {
throw new InvalidRequestException($decodedData);
}
// validate
$signatureRef = base64_encode(hash_hmac($this->HMAC_ALGO,$decodedData,$secretkey,true));
if ($signature === $signatureRef) {
return $jsonDecoded;
} else {
throw new InvalidSignatureException();
}
}
I made it work on iOS:
func hmac(_ algorithm: HMACAlgorithm, key: String) -> String {
let cKey = key.cString(using: String.Encoding.utf8)
let cData = self.cString(using: String.Encoding.utf8)
var result = [CUnsignedChar](repeating: 0, count: Int(algorithm.digestLength()))
CCHmac(algorithm.toCCHmacAlgorithm(), cKey!, Int(strlen(cKey!)), cData!, Int(strlen(cData!)), &result)
let hmacData:Data = Data(bytes: UnsafePointer<UInt8>(result), count: (Int(algorithm.digestLength())))
let hmacBase64 = hmacData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
print(String(hmacBase64))
return String(hmacBase64)
}
Any idea/help on doing this on Kotlin/Android? I'm being stuck on InvalidSignatureException error.
fun generateSignature(data : HashMap<String, Any>) : String {
val hmac = Mac.getInstance("HmacMD5")
hmac.init(SecretKeySpec(Constant.PRIVATEKEY.toByteArray(Charsets.UTF_8), hmac.algorithm))
return Base64.encodeToString(data.toString().toByteArray(),Base64.URL_SAFE + Base64.NO_PADDING + Base64.NO_CLOSE + Base64.NO_WRAP)
}
Thanks :D I really appreciate for any help :D
Update:
Just to make my question simpler?
Is it possible to make translate the iOS line of code to Kotlin?
enum HMACAlgorithm {
case md5, sha1, sha224, sha256, sha384, sha512
func toCCHmacAlgorithm() -> CCHmacAlgorithm {
var result: Int = 0
switch self {
case .md5:
result = kCCHmacAlgMD5
case .sha1:
result = kCCHmacAlgSHA1
case .sha224:
result = kCCHmacAlgSHA224
case .sha256:
result = kCCHmacAlgSHA256
case .sha384:
result = kCCHmacAlgSHA384
case .sha512:
result = kCCHmacAlgSHA512
}
return CCHmacAlgorithm(result)
}
func digestLength() -> Int {
var result: CInt = 0
switch self {
case .md5:
result = CC_MD5_DIGEST_LENGTH
case .sha1:
result = CC_SHA1_DIGEST_LENGTH
case .sha224:
result = CC_SHA224_DIGEST_LENGTH
case .sha256:
result = CC_SHA256_DIGEST_LENGTH
case .sha384:
result = CC_SHA384_DIGEST_LENGTH
case .sha512:
result = CC_SHA512_DIGEST_LENGTH
}
return Int(result)
}
}
this is how I call the function
var params : Dictionary
params.generateSignature()
fun generateSignature(data : HashMap) : String {
val hmac = Mac.getInstance("HmacMD5")
hmac.init(SecretKeySpec(Constant.PRIVATEKEY.toByteArray(Charsets.UTF_8), hmac.algorithm))
return Base64.encodeToString(data.toString().toByteArray(),Base64.URL_SAFE + Base64.NO_PADDING + Base64.NO_CLOSE + Base64.NO_WRAP)
}
Someone finally found out the answer.
My mistake is hashmap should be run under JSONObject
var obj = JsonObject(data)
and use obj.toString() :D
i need to know how to overgive parameters from HttpsWebRequestPost function to my php script.
LPCWSTR additionalHeaders = L"Content-Type: application/x-www-form-urlencoded\r\n";
DWORD headersLength = -1;
string HttpsWebRequestPost(string domain, string url, string dat)
{
//Extra
LPSTR data = const_cast<char *>(dat.c_str());;
DWORD data_len = strlen(data);
wstring sdomain = get_utf16(domain, CP_UTF8);
wstring surl = get_utf16(url, CP_UTF8);
string response;
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
BOOL bResults = FALSE;
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;
// Use WinHttpOpen to obtain a session handle.
hSession = WinHttpOpen(L"WinHTTP Example/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);
// Specify an HTTP server.
if (hSession)
hConnect = WinHttpConnect(hSession, sdomain.c_str(),
INTERNET_DEFAULT_HTTP_PORT, 0);
// Create an HTTP request handle.
if (hConnect)
hRequest = WinHttpOpenRequest(hConnect, L"POST", surl.c_str(),
NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
0);
// Send a request.
if (hRequest)
bResults = WinHttpSendRequest(hRequest,
additionalHeaders,
headersLength,
(LPVOID)data,
data_len,
data_len,
0);
// End the request.
if (bResults)
bResults = WinHttpReceiveResponse(hRequest, NULL);
// Keep checking for data until there is nothing left.
if (bResults)
{
do
{
// Check for available data.
dwSize = 0;
if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
printf("Error %u in WinHttpQueryDataAvailable.\n",
GetLastError());
// Allocate space for the buffer.
pszOutBuffer = new char[dwSize + 1];
if (!pszOutBuffer)
{
printf("Out of memory\n");
dwSize = 0;
}
else
{
// Read the data.
ZeroMemory(pszOutBuffer, dwSize + 1);
if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer,
dwSize, &dwDownloaded))
printf("Error %u in WinHttpReadData.\n", GetLastError());
else
//printf("%s", pszOutBuffer);
response = response + string(pszOutBuffer);
// Free the memory allocated to the buffer.
delete[] pszOutBuffer;
}
} while (dwSize > 0);
}
// Report any errors.
if (!bResults)
printf("Error %d has occurred.\n", GetLastError());
// Close any open handles.
if (hRequest) WinHttpCloseHandle(hRequest);
if (hConnect) WinHttpCloseHandle(hConnect);
if (hSession) WinHttpCloseHandle(hSession);
return response;
}
and the c++ code:
int main()
{
printf("%s", HttpsWebRequestPost("mywebspaceaddr", "test.php", "value=1000").c_str());
system("PAUSE");
return 0;
}
my php looks like this simple:
<?php
$val = $_GET['value'];
echo 'value given:' . $val;
?>
i recieve only the "value given:" text on console, but no value.
did anyone know how to display the value that was given by the function?
sry for my bad php knowledge :)
Your $_GET should be $_POST.
pretty easy, huh?
I need to validate a password in a Symfony 3.3 / FriendsOfSymfony UserBundle 1.3 application from an AWS Lambda function.
The relevant password hashing code in Symfony is here https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Security/Core/Encoder/MessageDigestPasswordEncoder.php#L52
However the code doesn't produce the same hashes even at the first line.
In Symfony with password=test, salt=asLZCFQJ5flTtOWdphjKtpngthjK6h2FtMRSIZZ2bus
$salted = $this->mergePasswordAndSalt($raw, $salt);
$digest = hash($this->algorithm, $salted, true);
//base64_encode($digest) == '2QhirHmPwt0O5MrtTdfWsWKCCeOQO/y02Di04/aUIJxWhdNDQSGCaUuL1ONLUasdsD88CBSIzGwsePqGTCcQmA=='
// "stretch" hash
for ($i = 1; $i < $this->iterations; ++$i) {
$digest = hash($this->algorithm, $digest.$salted, true);
}
With the same details in nodejs I get:
var pass='test';
var salt='asLZCFQJ5flTtOWdphjKtpngthjK6h2FtMRSIZZ2bus';
var salted = pass + '{' + salt + '}';
var digest = sha512.update(salted).digest('binary');
//new Buffer(digest).toString('base64') == 'w5kIYsKsecKPw4LDnQ7DpMOKw61Nw5fDlsKxYsKCCcOjwpA7w7zCtMOYOMK0w6PDtsKUIMKcVsKFw5NDQSHCgmlLwovDlMOjS1HCqx3CsD88CBTCiMOMbCx4w7rChkwnEMKY'
for (var i = 1; i < 5000; ++i) {
digest = require('crypto').createHash('sha512').update(digest + salted).digest('binary');
process.stdout.write(new Buffer(digest).toString('base64')+"\n");
}
or is this a character encoding problem? The first 3 characters of the binary hash look very similar in the debuggers.
Screenshot from PHPStorm
Screenshot from WebStorm
Finally i figured it out, hope it can help someone in the future.The issue comes from characters contact.
./middleware/passwordEncode.js:
const cryptoLib = require('crypto');
const encryptPassword = (password:any, salt:any) => {
let salted = password + '{' + salt + '}';
if (!salt){
salted = password;
}
let digest = cryptoLib.createHash('sha512').update(salted).digest('binary');
for (let i = 1; i < 5000; i++){
digest = cryptoLib.createHash('sha512').update( Buffer.concat([Buffer.from(digest, 'binary'), Buffer.from(salted, 'utf8')]) ).digest('binary');
}
return ( Buffer.from(digest, 'binary')).toString('base64');
}
module.exports.encryptPassword = encryptPassword;
./middleware/passwordDecode.js:
const passwordEncode = require('../middleware/passwordEncode')
const verifyPassword = (password:any, salt:any, encoded:any) => {
return encoded === passwordEncode.encryptPassword(password,salt);
}
module.exports.verifyPassword = verifyPassword
I have resolved this by switching the encryption method to bcrypt. This answer describes how to check the resulting password:https://stackoverflow.com/a/26643637/123594
im trying to establish secure RSA connection between PHP server and Unity 3D game (in Web Player). At the end of process $rsa->decrypt() return "false" :-(
Server generate RSA keys and send public key to Unity:
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
$keys = $rsa->createKey(512);
extract($keys);
$rsa->loadKey($publickey);
$_SESSION["privatekey"] = $privatekey;
$this->payload->Modulus = base64_encode($rsa->modulus);
$this->payload->Exponent = base64_encode($rsa->publicExponent);
This generate JSON:
{"Modulus":"MTE5MjcyOTYyNjQzMTIzODQ1MTI4MjE2ODA3OTY2MDE5MDQwODQ1NTc0MDIzMDI0NDQ5MjAzMDY4NDgxNTkyNzk5MTc0MzYxMzI4MDA3Njk0MjI4NjAyMzAwODA4MDI5MzkwOTk2MjUyMTg5OTkwNDgwNzg3MDcwMjk4MjkxMjcxNjQ1NzMzNDg0MTcxNTc0MDM3ODM0NjE3ODE=","Exponent":"NjU1Mzc="}
Unity ENCODER:
var N = JSON.Parse (generatedJSON); //im using SimpleJSON library
var publicKey = new RSAParameters ();
publicKey.Modulus = Convert.FromBase64String(N ["Modulus"].Value);
publicKey.Exponent = Convert.FromBase64String(N ["Exponent"].Value);
var csp = new RSACryptoServiceProvider(512);
csp.ImportParameters(publicKey);
var plainTextData = "Hello Wordl"; //here come AES key generator (not implemented yet)
var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(plainTextData);
var bytesCypherText = csp.Encrypt(bytesPlainTextData, false);
var cypherText = Convert.ToBase64String(bytesCypherText);
Unity response:
Nqsno9tTXWr4UfwoXQcHwzwnusvdKWpVGoakSsVECh3lH/3bNaPKY9LzZ9iZIs8RI9e5EI+GvegnxrW5xoqnyrDHbF8AuWh9Hndnn0OS5SV/kiYeBT6Wn9pxwjq5MoixM3geushHpvGTDQV0NOLcsXTdv8tG0CvFZip31GpMp9C/OalxolpaUvk65YBJ0dJcyNiuD08PQJAupJXKnVgfLZ0i1GrjQ7guHO6OmEUKDyQcZ5Sf/6yJry3Mhv2R4ioR/jU+mL4tLKuix5+/XKmBjg==
And server DECODER:
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
$rsa->loadKey($_SESSION["privatekey"]);
$message = $_POST["unityResponse"];
$ciphertext = base64_decode($message);
$this->payload->message = $rsa->decrypt($ciphertext);
Return "Decryption error in..." :(
I think general problem is in C#... Can you help me?
SOLVED!
By another way - XML key format
Server code:
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_XML);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_XML);
$keys = $rsa->createKey(1024);
extract($keys);
$rsa->loadKey($publickey);
$_SESSION["privatekey"] = $privatekey;
$this->payload->publickey = $publickey;
Generate JSON:
{"publickey":"<RSAKeyValue>\r\n <Modulus>sCL/O7uUl4T32nUxZhKj1svDG88k4jkGsh/7IiFX/kTbj3mXmtYPLn5xTyLxEt9FxA/aoVxBmh1k7wA7lvcu5z4Avw6+AA/j793iDEhGdfvmXmHxm05xkjYO+LZ449YGDst9DUDO8SDA948Rld+eA187d/nhVPPAmun7RbLXBrs=</Modulus>\r\n <Exponent>AQAB</Exponent>\r\n</RSAKeyValue>"}
Unity Web Player code:
var N = JSON.Parse (generatedJSON);
var csp = new RSACryptoServiceProvider(1024);
csp.FromXmlString (N ["publickey"]);
var plainTextData = "Hello from Web Player";
var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(plainTextData);
var bytesCypherText = csp.Encrypt(bytesPlainTextData, false);
var cypherText = Convert.ToBase64String(bytesCypherText);
And finally Server Decryption:
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_XML);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_XML);
$rsa->loadKey($_SESSION["privatekey"]);
$cypherText= $_POST["cypherText"];
$bytesCipherText = base64_decode($message);
$this->payload->encrypted = $rsa->decrypt($bytesCipherText);
And you get JSON:
{"message":"Hello from Web Player"}
Thanks for perfect phpsec library! Its epic!
I share my example Unity project here. Hoping that it is useful to some people ;)
GitHub: unity-php-secure-communication
<?php
<?php
/**
* test with curl:
*
* // Generate keypair : return XML public key
* curl -c cookies.txt -d "keygen=1" http://exemple.com//encrypt.php
*
* // Test encrypt/decrypt : return encrypted and decrypted `my text to encode`
* curl -b cookies.txt -d "test=my text to encode" http://exemple.com//encrypt.php
*
* // Test encrypt : return encrypted
* curl -b cookie.txt -d "encrypt=my text to encode" http://exemple.com//encrypt.php > encrypted.txt; cat encrypted.txt
*
* // Test decrypt : return decrypted `my text to encode`
* curl -b cookie.txt -d "decrypt=`cat encrypted.txt`" http://exemple.com//encrypt.php
*/
include 'vendor/autoload.php';
use phpseclib\Crypt\RSA;
function generateKeyPair(){
if (!isset($_SESSION['publickey'])){
$rsa = new RSA();
$rsa->setPrivateKeyFormat(RSA::PRIVATE_FORMAT_XML);
$rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_XML);
$keys = $rsa->createKey();
$_SESSION['privatekey'] = $keys['privatekey'];
$_SESSION['publickey'] = $keys['publickey'];
}
return $_SESSION['publickey'];
}
function encrypt($cleartext){
$rsa = new RSA();
$rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
$rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_XML);
$rsa->loadKey($_SESSION['publickey']);
$bytesCipherText = $rsa->encrypt($cleartext);
return rawurlencode(base64_encode($bytesCipherText));
}
function decrypt($encrypted){
$rsa = new RSA();
$rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
$rsa->setPrivateKeyFormat(RSA::PRIVATE_FORMAT_XML);
$rsa->loadKey($_SESSION['privatekey']);
$bytesCipherText = base64_decode(rawurldecode($encrypted));
return $rsa->decrypt($bytesCipherText);
}
if (isset($_POST['session_id'])) {
session_id($_POST['session_id']);
}
session_start();
if (isset($_POST['keygen'])) {
echo generateKeyPair();
exit();
}
if (isset($_POST['encrypt'])) {
echo encrypt($_POST['encrypt']);
exit();
}
if (isset($_POST['decrypt'])) {
echo decrypt($_POST['decrypt']);
exit();
}
if (isset($_POST['test'])) {
generateKeyPair();
$ciphertext = encrypt($_POST['test']);
echo "encrypted: $ciphertext\n\n";
$clearText = decrypt($ciphertext);
echo "decrypted: $clearText\n";
exit();
}
using System;
using System.Collections;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
using UnityEngine.Analytics;
using UnityEngine.Networking;
using UnityEngine.UI;
public class EncryptController : MonoBehaviour
{
public string ScriptUrl = "http://example.com/encrypt.php";
public InputField ClearTextInputField;
public InputField EncryptedTextInputField;
public InputField ClearResponseInputField;
public Text SessionIdText;
public Text PublicKeyText;
public void OnKeygenButtonClick()
{
StartCoroutine(GenerateRsaKeyPair());
}
public void OnEncryptButtonClick()
{
if (PublicKeyText.text.Length < 100)
{
Debug.LogError("You must generate RSA key pair before");
return;
}
var csp = new RSACryptoServiceProvider(1024);
csp.FromXmlString(PublicKeyText.text);
var plainTextData = ClearTextInputField.text;
var bytesPlainTextData = Encoding.Unicode.GetBytes(plainTextData);
var bytesCypherText = csp.Encrypt(bytesPlainTextData, false);
var cypherText = Convert.ToBase64String(bytesCypherText);
EncryptedTextInputField.text = cypherText;
}
public void OnDecryptButtonClick()
{
if (PublicKeyText.text.Length < 100)
{
Debug.LogError("You must generate RSA key pair before");
return;
}
StartCoroutine(SendEncryptedText(EncryptedTextInputField.text));
}
IEnumerator GenerateRsaKeyPair()
{
var form = new WWWForm();
form.AddField("keygen", 1);
form.AddField("session_id", AnalyticsSessionInfo.sessionId.ToString());
SessionIdText.text = "sessionId=" + AnalyticsSessionInfo.sessionId.ToString();
using (var www = UnityWebRequest.Post(ScriptUrl, form))
{
yield return www.SendWebRequest();
if (www.isNetworkError)
{
Debug.LogError(www.error);
}
else
{
LogHeaders(www);
Debug.Log(www.downloadHandler.text);
PublicKeyText.text = www.downloadHandler.text;
}
}
}
IEnumerator SendEncryptedText(string text)
{
var form = new WWWForm();
form.AddField("decrypt", text);
form.AddField("session_id", AnalyticsSessionInfo.sessionId.ToString());
SessionIdText.text = "sessionId=" + AnalyticsSessionInfo.sessionId.ToString();
using (var www = UnityWebRequest.Post(ScriptUrl, form))
{
//www.SetRequestHeader("cookie", SessionIdText.text);
yield return www.SendWebRequest();
if (www.isNetworkError)
{
Debug.LogError(www.error);
}
else
{
LogHeaders(www);
// Print Body
Debug.Log(www.downloadHandler.text);
ClearResponseInputField.text = www.downloadHandler.text;
}
}
}
private void LogHeaders(UnityWebRequest www)
{
var sb = new StringBuilder();
foreach (var dict in www.GetResponseHeaders())
{
sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n");
if (dict.Key == "Set-Cookie")
{
SessionIdText.text = dict.Value + " (from response headers)";
}
}
Debug.Log(sb.ToString());
}
}
I need to convert this pice of PHP code to swift to create hashes, I am using a hash pattern in PHP to hash 2 strings with SHA256 and I would like to do this in swift, any ideas?
The SELF::SECRET is a secret key, and the SELF::HASH_PATTERN is my pattern and looks something like this: "00101010011100001010"
public function hash($first, $second) {
// Append the secret to the values.
$first = self::SECRET . $first;
$second = $second . self::SECRET;
// Hash the values.
$hash = hash_init('sha256');
hash_update($hash, $first);
$hash1 = hash_final($hash);
$hash = hash_init('sha256');
hash_update($hash, $second);
$hash2 = hash_final($hash);
// Create a new hash with pieces of the two we just made.
$result = '';
for ($i = 0; $i < strlen(self::HASH_PATTERN); $i++) {
$result .= substr(self::HASH_PATTERN, $i, 1) ? $hash2[$i] : $hash1[$i];
}
return $result;
}
Thanks!
UPDATE:
This is the part which I can't figure out:
$hash = hash_init('sha256');
hash_update($hash, $first);
$hash1 = hash_final($hash);
UPDATE:
After a few hours of doing research and coding I finally got it figured out.
This is the code that I wrote, maybe not the best, but it works :)
I used a small class from github for generating SHA256 strings in swift called NSHash
func create_token(first:String, second:String) -> String {
var newFirst = constants.secret + first as NSString
var newSecond = second + constants.secret as NSString
var hash1 = newFirst.SHA256()
var hash2 = newSecond.SHA256()
var result = ""
for var i = 0; i < countElements(constants.hash_pattern); i++ {
var character = "\(constants.hash_pattern[i])" as String
var number:Int = character.toInt()!
if number == 1 {
result = "\(result)\(hash2[i])"
}else {
result = "\(result)\(hash1[i])"
}
}
return result
}