Encrypting in VB.Net and Decrypting in PHP - php

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.

Related

Decrypting VB.Net (14) System.Security.Cryptography salted password in PHP to Login to Android App

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.

Openssl encrypted in PHP needs to be decrypted in Ruby

In our application we are getting encrypted text from external server. This text have been encrypted using openssl in php.
When I am trying to decrypt the text in my Ruby code, I am getting following error message:
OpenSSL::Cipher::CipherError: wrong final block length
I read couple of solutions on Stackoverflow and was suggest to add following line to the code cipher.padding = 0. But after adding padding = 0, I am getting different error:
OpenSSL::Cipher::CipherError: data not multiple of block length
Below is my rough script I have written to decrypt the code.
require 'openssl'
require 'digest/sha1'
require 'base64'
encrypted = "VaZYJzn9QVEQIH4fmtA1Cg=="
key = "my_secret_key"
cipher = OpenSSL::Cipher::Cipher.new("aes-128-ecb")
cipher.decrypt
cipher.padding = 0
cipher.key = key
decrypted = cipher.update(encrypted)
decrypted << cipher.final
puts Base64.decode64(decrypted)
If I encrypt the text using Ruby then I can easily decrypt it. I am having problem to decrypt the code which are encrypted in php. Is there any way I can make encryption and decryption compatible between php and Ruby.
Simply change the way you call it.
From decrypted << cipher.final to decrypted = cipher.update(encrypted) + cipher.final
could get the string like
<GF\x8F\xDC\x91\xE1ew\xB1\x1C\xE8\xF8V\xA0\x99g\x01C\xCDF\xD6\v\x841l\x13\xA6\x9496{
Last, quote from Ruby Doc You should never use ECB mode unless you are absolutely sure that you absolutely need it

Decrypt a file in php which is encrypted in android

I encrypted a file in android using triple des. This file is uploaded to the server using php. Have to write php script to decrypt the same file.
New to php, any help would be appreciated with php scripts.
public void encrypt(InputStream in, OutputStream out) throws Exception {
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec param = new IvParameterSpec(iv);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, param);
// Read in the cleartext bytes and write to out to encrypt
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
byte[] output = cipher.doFinal(buf, 0, numRead);
if(output != null) {
byte[] enc = Base64.encode(output, 0);
out.write(enc);
}
}
out.close();
}
I'm passing hard coded values for keyBytes and iv which are hexadecimal values.
So, it seems like you are going to have to use the mcrypt extension. The mcrypt extension supports TRIPLEDES.
Installation
List of ciphers supported by mcrypt.
Here are some mcrypt examples.
The mcrypt function to decrypt is here.
I'm currently learning android and advanced php. If you are new to php, I highly recommend going to php.net for everything. It's been very helpful for me.

Convert VB.NET Encryption Method to PHP

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.

exchange aes 256 encrypted data between php and flex

I need 2 sets of encrypt/decrypt functions to run under PHP and AS3.
I found AS3Crypto (for Flex) and mcrypt_encrypt (for PHP) and this article that shows how to use them for DES encryption:
http://www.zedia.net/2009/as3crypto-and-php-what-a-fun-ride/
I then tried to replace the DES encryption with AES-256, because the DES seems too vulnerable to brute force attacks.
The results from AES encryption in Flex and PHP are different.
Does anyone know (and tested) any equivalent functions for aes encryption in as3 and php?
If I wasn't clear enough, here is another post of an user having the same problem:
http://forum.openlaszlo.org/showthread.php?t=13709
Thanks!
I've done similar with different back end's and it can be a headache to get them to match.
I will tell you with a high degree of confidence from experience that most likely the issue you're running into is that the padding isn't matching up between the two or the encoding going back and forth (Hex).
Here's some working coldfusion code from an implementation I did a couple years ago, quickest I could dig up...
<cfsetting enablecfoutputonly="yes">
<cfparam name="form.k" default="1bbee91984f8b5bc032b6f67a665704e"/>
<cfscript>
textToEncrypt = 'printButton=No&saveButton=No';
encKey = ToBase64(BinaryDecode(form.k,"Hex"));
encryptedText = encrypt(textToEncrypt, encKey, 'AES', 'Hex');
</cfscript>
<cfoutput>settings=#encryptedText#</cfoutput>
(side note: isnt coldfusion awesome? hehe :P)
The decryption side in flex :
private function settingsEncResponse( e : ResultEvent ) : void {
// decrypt settings string
var o : Object = e.result;
var k:String = pKey; // key to decrypt with
var kdata:ByteArray;
kdata = Hex.toArray(k);
var txt:String = o.settings; // text to decrypt
var data:ByteArray;
data = Hex.toArray(txt);
var pad:IPad = new PKCS5;
var mode:ICipher = Crypto.getCipher("aes-ecb", kdata, pad);
pad.setBlockSize(mode.getBlockSize());
mode.decrypt(data);
currentInput = data;
var decryptedSettings : String = Hex.toString(Hex.fromArray(currentInput));

Categories