I have this code from our old system in .NET, and I need to rewrite it in PHP.
try{
byte[] heslo = Encoding.UTF8.GetBytes(Pwd);
byte[] salt = Encoding.UTF8.GetBytes(String.Format("source={0}&owner={1}&usercode={2}&ts={3}", Source, Owner, UserCode, ts));
int iterations = 8;
byte[] output = null;
using (var hmac = new HMACSHA256()){
var df = new Pbkdf2(hmac, heslo, salt, iterations);
output = df.GetBytes(20);
token.Value = BitConverter.ToString(output).Replace("-", "").ToLowerInvariant();
}
}catch{
token = null;
}
return token;
}
I tried to use
openssl_pbkdf2( $password,$salt,20,8,"SHA256");
with the same values in both scripts but in php I'm getting different output, can anyone help me. Please
Related
Itext is a powerful toolkit for PDF generation, PDF programming, handling & manipulation. Java sample:
public void processPDF(String src, String dest) {
try {
PdfReader reader = new PdfReader(src);
PdfArray refs = null;
PRIndirectReference reference = null;
int nPages = reader.getNumberOfPages();
for (int i = 1; i <= nPages; i++) {
PdfDictionary dict = reader.getPageN(i);
PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
if (object.isArray()) {
refs = dict.getAsArray(PdfName.CONTENTS);
ArrayList<PdfObject> references = refs.getArrayList();
for (PdfObject r : references) {
reference = (PRIndirectReference) r;
PRStream stream = (PRStream) PdfReader.getPdfObject(reference);
byte[] data = PdfReader.getStreamBytes(stream);
String dd = new String(data, "UTF-8");
dd = dd.replaceAll("#pattern_1234", "trueValue");
dd = dd.replaceAll("test", "tested");
stream.setData(dd.getBytes());
}
}
if (object instanceof PRStream) {
PRStream stream = (PRStream) object;
byte[] data = PdfReader.getStreamBytes(stream);
String dd = new String(data, "UTF-8");
System.out.println("content---->" + dd);
dd = dd.replaceAll("#pattern_1234", "trueValue");
dd = dd.replaceAll("This", "FIRST");
stream.setData(dd.getBytes(StandardCharsets.UTF_8));
}
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
reader.close();
}
catch (Exception e) {
}
}
The question is how I can use this toolkit for PHP or there is any PHP toolkit like this?
I am using Yii2 Framework and just want to replace text inside a certain file (.doc, .docx, .pdf)
Original file:
Expected file after editing:
I have this piece of code which is in java but i want it in php .
there is a function to convert hex to byte . and a main code:
public static byte[] ConvertHexStringToByteArray(String s)
{
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2)
{
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
and here is main code :
public static String hmacSha1(String value, String key)
{
try
{
// Get an hmac_sha1 key from the raw key bytes byte[]
keyBytes = ConvertHexStringToByteArray(key);
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
// Get an hmac_sha1 Mac instance and initialize with the signing
key Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
// Compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(value.getBytes(StandardCharsets.US_ASCII));
// Convert raw bytes to Hex
byte[] hexBytes = new Hex().encode(rawHmac);
// Covert array of Hex bytes to a String
return new String(hexBytes, "UTF-8");
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
Hello
Your Java code in php is same as blow :
$key = strtolower($CPCode.$service_id.$price.$timestamp.$request_id);
$authKey = $CPCode;
$sign = hash_hmac("sha1",$key,$authKey);
Good Luck
I don't really want to dump some code and expect answers but this is a pretty lengthy function that hashes a password in order to later compare it to the database-stored value.
I have seen posts where people wasted time trying to recreate what they could achieve with the md5() function in PHP.
For that reason, I'm wondering if someone with any encryption knowledge knows of a PHP equivalent to achieve the following effect in PHP:
internal static string GenerateEncryptedPassword(string password, string salt, int iterationCount)
{
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] saltBytes = Encoding.UTF8.GetBytes(salt);
byte[] iterationCountBytes = BitConverter.GetBytes(iterationCount);
int derivedLength = passwordBytes.Length + saltBytes.Length;
byte[] passwordSaltBytes = new byte[derivedLength];
byte[] pbkdf2Bytes;
string encryptedString;
for (int i = 0; i < passwordBytes.Length; i++)
{
passwordSaltBytes[i] = passwordBytes[i];
}
for (int i = 0; i < saltBytes.Length; i++)
{
passwordSaltBytes[passwordBytes.Length + i] = saltBytes[i];
}
using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, passwordSaltBytes, iterationCount))
{
pbkdf2Bytes = pbkdf2.GetBytes(derivedLength + iterationCountBytes.Length);
}
using (SHA512 sha512 = new SHA512Managed())
{
byte[] hashBytes = sha512.ComputeHash(pbkdf2Bytes);
byte[] hashSaltBytes = new byte[hashBytes.Length + saltBytes.Length];
for (int i = 0; i < hashBytes.Length; i++)
{
hashSaltBytes[i] = hashBytes[i];
}
for (int i = 0; i < saltBytes.Length; i++)
{
hashSaltBytes[hashBytes.Length + i] = saltBytes[i];
}
encryptedString = Convert.ToBase64String(hashSaltBytes);
}
return encryptedString;
}
If it changes anything, I'm using Laravel...
Thank you for any guidance
I hate encryption :D
$user = \App\User::all();
$salt = strtolower($user[2]->Salt);
$password = 'P#$$W0rd';
$dbPassword = $user[2]->Password;
$iterations = 10000;
echo openssl_pbkdf2($password, $salt, 44, $iterations, 'sha512');
Read the PHP manual for password_hash and password_verify. I recommend using BCrypt as the algorithm.
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php
It's not difficult at all! Good luck! :-)
Also, SHA-512 isn't all that secure. Read here: SHA1 vs md5 vs SHA256: which to use for a PHP login?
I haven't used PHP for years so not sure if there are new ways to do things, but you can produce SHA-512 hashes with OpenSSL: http://php.net/manual/en/function.openssl-digest.php
openssl_digest(pbkdf2Bytes, 'sha512');
To generate salt, it is highly recommended to use secure (unpredictable) randoms. For PHP, see this: PHP random string generator
EDIT:
You can also produce pbkfd2 directly with OpenSSL:
http://php.net/manual/en/function.openssl-pbkdf2.php
Just note the optional parameter in the end of the function signature where you define the digest algorithm.
openssl_pbkdf2(password, saltBytes, keyLength, iterationCount, 'sha512')
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 have a program that encrypts passwords using a c# rsa public key which outputs a byte array.
In order for me to transport it easily and maintain data I am converting the bytes directly to a Hex string. Now this is where I am having issue. I send the post data to my script and am now unsure what to convert it to and how to decrypt it.
I am attempting to use http://phpseclib.sourceforge.net/ which I was pointed to by this post RSA decryption using private key The documentation on this is very vague and I don't know what data/type decrypt() should take.
<?php
include('Crypt/RSA.php');
if (isset($_POST['Password']))
{
$Password = $_POST['Password'];
$crypttext = pack("H*",$Password);
echo $cryptext;
$rsa = new Crypt_RSA();
$rsa->loadKey('key.priv');
$decryptedText =$rsa->decrypt($cryptext);
echo "Pass = >" . $decryptedText;
}
?>
Note that this gives no errors but $decryptedText is empty.
EDIT: Adding more info.
This is my c# encrypt method.
public static string Encrypt(string data, string keyLocation, string keyName)
{
Console.WriteLine("-------------------------BEGIN Encrypt--------------------");
// Variables
CspParameters cspParams = null;
RSACryptoServiceProvider rsaProvider = null;
string publicKeyText = "";
string result = "";
byte[] plainBytes = null;
byte[] encryptedBytes = null;
try
{
// Select target CSP
cspParams = new CspParameters();
cspParams.ProviderType = 1; // PROV_RSA_FULL
rsaProvider = new RSACryptoServiceProvider(2048, cspParams);
// Read public key from Server
WebClient client = new WebClient();
Stream stream = client.OpenRead(keyLocation + "/" + keyName);
StreamReader reader = new StreamReader(stream);
publicKeyText = reader.ReadToEnd();
//
//Console.WriteLine("Key Text : {0}",publicKeyText);
// Import public key
rsaProvider.FromXmlString(publicKeyText);
// Encrypt plain text
plainBytes = Convert.FromBase64String(data);
Console.WriteLine("inputlength : {0}",plainBytes.Length);
encryptedBytes = rsaProvider.Encrypt(plainBytes, false);
result = ByteArrayToString(encryptedBytes);
Console.WriteLine("Encrypted Hex string : {0}", result);
}
catch (Exception ex)
{
// Any errors? Show them
Console.WriteLine("Exception encrypting file! More info:");
Console.WriteLine(ex.Message);
}
rsaProvider.Dispose();
Console.WriteLine("-------------------------END Encrypt--------------------");
return result;
} // Encrypt
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length / 2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hex))
{
for (int i = 0; i < NumberChars; i++)
bytes[i] =
Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
}
return bytes;
}
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
I modified the php to this
<?php
include('Crypt/RSA.php');
if (isset($_POST['Password']))
{
$Password = $_POST['Password'];
$crypttext = pack("H*",$Password);
echo $cryptext;
$rsa = new Crypt_RSA();
$rsa->loadKey(file_get_contents('key.priv')); // Added file_get_contents() which fixed the key loading
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); // Added this which is essential thank you guys/gals
$decryptedText =$rsa->decrypt($cryptext);
echo "Pass = >" . $decryptedText; // gives unsual data. This needs to be converted from binary data to base64string I think
echo "Pass = >" . base64_encode($decryptedText); // gives no data.
echo "Pass = >" . base64_decode($decryptedText); // gives no data.
}
?>
I searched around and tried several things to convert back to text and I have tried base64_encode() and base64_decode() but I get nothing and otherwise I get gobbledey gook.
The final solution was to use imap_binary($decryptedText) to convert back.
Edit :
It has since been brought to my attention that a better way of doing this would be to replace 2 things
C#
plainBytes = Convert.FromBase64String(data);
Changed to
plainBytes = Encoding.UTF8.GetBytes(data);
and PHP
imap_binary($decryptedText)
Changed to
utf8_decode($decryptedText)