Was hoping someone would be able to help me out.
I desperately need this VB.NET code converted to PHP.
This is the Instructions I received:
To test your encryption, encrypt the following word with these keys and check if you get the same result:
Text to encrypt: MyPassword
Salt key: *&^%$##!
PBE Key: FWV70700
PBE IV: WEBSV
NOTE:
Encrypted text: A+V3JATKUt/T91HiF23eOA==
Following is a short VB.Net code snippet that will do the encryption, as we need it. The VB program has a form (From1) with two text boxes (TextBox1 and TextBox2) and one button (Button1):
VB.NET Function:
Imports System
Imports System.IO
Imports System.Xml
Imports System.Text
Imports System.Security.Cryptography
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox2.Text = EncryptText(TextBox1.Text)
End Sub
Public Shared Function EncryptText(ByVal strText As String) As String
Dim pdbPassword As PasswordDeriveBytes
Dim pdbIV As PasswordDeriveBytes
Dim DES As New DESCryptoServiceProvider
Dim salt() As Byte = {Asc("*"), Asc("&"), Asc("^"), Asc("%"), Asc("$"), Asc("#"), Asc("#"), Asc("!")}
Dim ms As New System.IO.MemoryStream
Dim cs As CryptoStream
Dim plainText As String = strText
Dim plainBytes() As Byte
plainBytes = System.Text.Encoding.UTF8.GetBytes(plainText)
pdbPassword = New PasswordDeriveBytes("FWV70700", salt)
pdbPassword.HashName = "SHA1"
pdbPassword.IterationCount = 1000
DES.Key = pdbPassword.GetBytes(8)
pdbIV = New PasswordDeriveBytes("WEBSV", salt)
pdbIV.HashName = "SHA1"
pdbIV.IterationCount = 1000
DES.IV = pdbIV.GetBytes(8)
cs = New CryptoStream(ms, DES.CreateEncryptor, CryptoStreamMode.Write)
cs.Write(plainBytes, 0, plainBytes.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray)
End Function
Could someone PLEASE convert this to PHP for me?
You need to find the according functions that do the same in PHP and then code it in PHP. It's best to do this step by step so you can compare if it's already working or not. As you have the vb.net code you can do this.
Sometimes functions vary a bit between .net and PHP, so there might be specific issues you need to take care about, so better do everything step by step and double checked.
See as well this related question: Same string, different SHA1 hash values obtained from VB.net and PHP.
Related
Hello everyone i was trying to decrypt some encrypted strings i encrypted with python .
the problem is that sometimes it decrypts correctly and sometimes it gives empty output for no obvious reason and i couldn't find any solution for it.
here's the code i'm using to decrypt on PHP .
knowing that online AES decryption tools decrypts it correctly.
$rtk=base64_decode('zgdHfETipvp1E5m3ix5NFOLuX8N0+zAIBzg+GOq0cTQ=');
$method = "aes-128-ecb";
$key = 'aaaaaaaaaaaaaaaa';
$email=openssl_decrypt($rtk, $method, $key,OPENSSL_RAW_DATA);
i would apreciate your help !
EDIT :
The python code i used to encript the string :
import pandas as pd
from Crypto.Cipher import AES
import names
import urllib.parse
import base64
from Crypto.Util.Padding import pad
from Crypto.Util.Padding import unpad
email="zqeafzeqaf23#example1.com"
key = b'aaaaaaaaaaaaaaaa'
data = email.encode('ascii', 'ignore')
cipher = AES.new(key, AES.MODE_ECB)
b64string = base64.urlsafe_b64encode(cipher.encrypt(pad(data,16)))
print(b64string)
Your Python code uses urlsafe_b64encode, but your PHP code uses the normal base64 variant (in fact your example data in the PHP code contains a + character so couldn’t have been produced by that Python code).
This could explain why the decryption is failing. If the url safe base 64 output from Python contains a - or _ character, PHP will simply strip that character from the string before decoding the rest of it. This will leave a string that is not a multiple of the AES block length and the decryption will fail.
You should ensure you are using the same base 64 variant to encode and decode. It doesn’t look like PHP provides a URL safe variant, you might need to use something like strtr before decoding to convert the base 64 into a normal variant:
$data = strtr($data, '-_', '+/');
$decoded = base64_decode($data);
I am working on creating an PHP String decrypter for a program that is written in VB.Net. I have done some research on .NET to PHP Encryption and Decryption and I can't seem to find a definitive solution.
I am new to PHP and my strong suit is not in Cryptography. It seems like their is a lot of different encryption classes.(mcrypt, Openssl and Sodium)
Here is the Code that I was given for the VB.Net Application.
Public Shared Function DecryptString(ByVal cipherTextStringWithSaltAndIv As String, ByVal passPhrase As String) As String
Dim cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherTextStringWithSaltAndIv)
Dim saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray()
Dim ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray()
Dim cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray()
Dim key As New Rfc2898DeriveBytes(passPhrase, saltStringBytes, 1000)
Dim keyBytes = key.GetBytes(Keysize / 8)
Using symmetricKey As New RijndaelManaged()
symmetricKey.BlockSize = 256
symmetricKey.Mode = CipherMode.CBC
symmetricKey.Padding = PaddingMode.ISO10126
Using decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes)
Using memoryStream As New MemoryStream(cipherTextBytes)
Using cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}
Dim decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)
memoryStream.Close()
cryptoStream.Close()
Return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)
End Using
End Using
End Using
End Using
End Function
This is the function that I am unable to replicate in PHP.
So what I am looking for specifically.
Which Class/Extension? should I be using to receive an encrypted string and decrypt it to get the same results as this VB.Net function.
If you have any examples of how to solve this issue or any links to articles that would help me understand this issue further I would be
very grateful.
Thanks.
You can use (as you already said) Sodium!
Sodium for .NET
Also you should check out how does the Public-key authenticated encryption works. This is what you need. This system provides mutual authentication. However, a typical use case is to secure communications between a server, whose public key is known in advance, and clients connecting anonymously.
The code is written in C# but is it not a big deal to translate it. Die lib itself works without problems in vb.net
EDIT: I translated the example for you:
Private Sub GetStarted()
Const MESSAGE As String = "hello bob"
Dim vbnet As Sodium.KeyPair = Sodium.PublicKeyBox.GenerateKeyPair()
Dim php As Sodium.KeyPair = Sodium.PublicKeyBox.GenerateKeyPair()
Dim nonce As Byte() = Sodium.PublicKeyBox.GenerateNonce()
'vbnet encrypts A message for php
Dim encrypted As Byte() = Sodium.PublicKeyBox.Create(MESSAGE, nonce, vbnet.PrivateKey, php.PublicKey)
'php decrypt the message
Dim decrypted As Byte() = Sodium.PublicKeyBox.Open(encrypted, nonce, php.PrivateKey, vbnet.PublicKey)
'make the bytes readable
Dim msg As String = System.Convert.ToBase64String(decrypted)
decrypted = Convert.FromBase64String(msg)
msg = System.Text.Encoding.UTF8.GetString(decrypted)
MsgBox(msg)
End Sub
For php you should check the PHP String Encryption Example with Libsodium in this answer.
I have read up on tons of samples and answers (and even more on how cryptography works) but none answers my scenario. I am creating a new user from desktop app in VB.Net. User need to use Android for a small part to update a valuation where a PC is not available (Web app is not an option unfortunately)
I have no problem in desktop app, all works fine. I am using a PHP page to handle the login and other data related actions in Android, also no problem. I did however had to change password to normal strings etc to read the passwords. I need to let PHP read the saved salted string (different salt for each password - all randomly generated, no salt the same for more than 1 user) linked to that particular password.
I have played around with the code for some time now to try and use the same kind of function in PHP but I am totally lost on how to convert the .net part to be used in PHP.
My .net code looks like this -
Imports System.Security.Cryptography
Imports System.Text
Module modSecurity
Public Function GetSaltedHash(pw As String, salt As String) As String
Dim tmp As String = pw & salt
' or SHA512Managed
Using hash As HashAlgorithm = New SHA256Managed()
' convert pw+salt to bytes:
Dim saltyPW = Encoding.UTF8.GetBytes(tmp)
' hash the pw+salt bytes:
Dim hBytes = hash.ComputeHash(saltyPW)
' return a B64 string so it can be saved as text
Return Convert.ToBase64String(hBytes)
End Using
End Function
Public Function CreateNewSalt(size As Integer) As String
' use the crypto random number generator to create
' a new random salt
Using rng As New RNGCryptoServiceProvider
' dont allow very small salt
Dim data(If(size < 7, 7, size)) As Byte
' fill the array
rng.GetBytes(data)
' convert to B64 for saving as text
Return Convert.ToBase64String(data)
End Using
End Function
Within my form I will create the hashed password and salt as follow -
strPasswordNew = txtPassword.Text
Dim NewPWD As String = strPasswordNew ''Actual password
strSaltPWD = CreateNewSalt(SaltSize) ''Salt pwd
Dim SaltPWDHash As String = GetSaltedHash(NewPWD, strSaltPWD) ''New pwd now hashed
The password and the salt is saved to database under their own fields - salt and pwd.
Any pointers will be highly appreciated please.
I'm migrating a web service that was developed in VB.NET to PHP
I explain:
In VB. NET I have a method that compresses a single string with GZIP. ("Hello world!")
The method in the web service returns an array of bytes.
Then the array of bytes is received on a device with android, decompressed and converted to a string, this process works perfect.
the method in VB.NET, is this:
<WebMethod(Description:="GZIP Test")> _
Public Function GZIP() As Byte()
Dim vTest As String = "Hello world!"
Dim vBuffer1() As Byte = StrToByteArray(vTest)
Dim vBuffer2() As Byte = Compress(vBuffer1)
Return vBuffer2
End Function
Private Function StrToByteArray(ByVal str As String) As Byte()
Dim encoding As New System.Text.UTF8Encoding()
Return encoding.GetBytes(str)
End Function
Private Function Compress(ByVal Bits() As Byte) As Byte()
On Error Resume Next
Using ms As New MemoryStream(), zipMem As New GZipStream(ms, CompressionMode.Compress, True)
zipMem.Write(Bits, 0, Bits.Length)
zipMem.Close()
Return ms.ToArray
End Using
End Function
this method returns me the following value:
<base64Binary>H4sIAAAAAAAEAO29B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/Ir6dl2WVXlV1Oftd/x+VGYUbDAAAAA==</base64Binary>
I want PHP return me the SAME VALUE.
the tests I've done in PHP returns me the following.
function GZIP() {
ob_start ( 'ob_gzhandler' );
return base64_encode(gzdeflate('Hello world!', 9));
}
the value returned in PHP is:
80jNyclXKM8vyklRBAA=
Why ? There is an example that returns the same ?
Thanks in advance for all.
You are using the wrong de-/compression algorithm. Use phps gzcompress() and gzuncompress() instead.
First off, you can't require the exact same result. All you can require of a lossless compressor is that it reproduce exactly the same input when decompressed.
Second, you want to use gzencode to produce gzip streams. Neither gzdeflate nor gzcompress will do that. The former produces raw deflate streams, and the second zlib streams. (Don't get me started about the misleading names and the messed up PHP documentation about them.)
I need to do this with php encryption method.
turkey 3d a bank payment module in the code for the example given to me in this way encryption.
could you help me translate this into php code?
SHA1 sha1 = new SHA1CryptoServiceProvider();
byte[] notHashedBytes = System.Text.Encoding.ASCII.GetBytes(notHashedStr);
byte[] hashedByte = sha1.ComputeHash(notHashedBytes);
string hashedStr = System.Convert.ToBase64String(hashedByte);
return hashedStr;
I know nothing about .Net but from what I gathered in this page seems like the PHP equivalent is just:
$hashedStr = base64_encode(sha1($notHashedStr, true));
You need to encode the raw binary format and not the hexadecimal representation.