Decrypt a file in php which is encrypted in android - php

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.

Related

Encrypting in VB.Net and Decrypting in 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.

Encrypt Decrypt Python PHP convert AES

I have this issue where something is encrypted in python using aes 256 cbc encryption as shown in the python codes encrypt method .
I am trying to create a Decrypt method in php to actually decrypt whats encrypted using the python class .
Here is my attempt to convert the python decryption method to php does it look right or am I missing something in my conversion as every time i use the php version to decrypt it says hmac failed ?
anyhelp in converting the python class to php i will appreciate.
public function decrypt(){
$encrypt_method ="AES-256-CBC";
$secret_key =base64_decode('samekeyusedintheencryption');
$encrypted=(string)'some encrypted text to be decrypted';
$data=json_decode(base64_decode($encrypted),true);
$secret_iv =base64_decode($data['iv']);
$output = \openssl_decrypt($data['value'],
$encrypt_method,$secret_key,0,$secret_iv);
return json_encode($output);
}
def decrypt(self, payload):
data = json_c.decode(base64.b64decode(payload))
value = base64.b64decode(data['value'])
iv = base64.b64decode(data['iv'])
crypt_object=AES.new(self.key,AES.MODE_CBC,iv)
plaintext = crypt_object.decrypt(value)
return loads(plaintext)
OK, I got it to work!
function decrypt($encryptedText, $secret_key){
$secret_key = base64_decode($secret_key);
$encrypt_method ="AES-256-CBC";
$data = json_decode(base64_decode($encryptedText),true);
$data['iv'] = base64_decode($data['iv']);
$data['value'] = base64_decode($data['value']);
return openssl_decrypt($data['value'], $encrypt_method, $secret_key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $data['iv']);
}
Some things I learned:
If the options in the openssl function are set to '0' it expects a base64_encoded input for the cipher text. Also, if the default options is set to '0' the padding default is set to PKCS#7. This, I think, is why we were getting the bad block size error.
So, the cipher text needs to be base64_decoded and we need to set both options for the padding.
I was able to decrypt your provided cipher text and see the email addresses.
You are provided the MAC in the Data array so this would allow you to check the MAC in the PHP script. This allows you to make sure the data has not been tampered with.
I recently did an encryption project and started with the open ssl, but ended up changing to the libSodium library. I highly recommend you check it out for any further projects.
Cheers!

ASN.1 encoding routines:OPENSSL_internal:WRONG_TAG

What does this error mean:
java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0000b9:ASN.1 encoding routines:OPENSSL_internal:WRONG_TAG
my code is:
public static byte[] encryptByPublicKey(byte[] data, String key)
throws Exception {
key = key.replace("-----BEGIN RSA PUBLIC KEY-----\r\n", "").replace("-----END RSA PUBLIC KEY-----", "");
byte[] bytes = decryptBASE64(key);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(bytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey pkPublic = keyFactory.generatePublic(x509KeySpec);
Cipher pkCipher = Cipher.getInstance("RSA");
pkCipher.init(Cipher.ENCRYPT_MODE, pkPublic);
return pkCipher.doFinal(data);
}
I'm sure, i have the correct data and key (that created in php), but i get this error in line:
PublicKey pkPublic = keyFactory.generatePublic(x509KeySpec);
I don't have any problem whit this code in my other android (without php server)apps, and i have correct answer by the same encryption/decryption code.
Is it possible that a function using in two projects, with the same input an output values, in the same software, has different actions? Yes! it's possible, but how about Android Studio, and Phpstorm? Is it about Openssl cer.? or other libraries? or some other reasons? How can I overcome this error?
I appreciate it if you help me. Thanks in advance for your answers.
Please check the key string, maybe contains illegal Base64 char: "\n", "\t", or \s and so on, remove them and try again !

encrypt and decrypt with phpseclib using rsa public and private key , getting decryption error

phpseclib:
php code :
include('Crypt/RSA_XML.php');
$rsa = new Crypt_RSA_XML();
$rsa->loadKeyfromXML($public_key_xml);
$data = "invoice_number=1,100.00&customer_tin=674858994885&serial=ONLYPEMPSERIAL&tin=ONLYPUMPTIN&vat_1_net=2,0000&vat_1_value=3600&vat_2_net=0&vat_2_value=0&vat_3_net=0&vat_3_value=0&vat_4_net=0&vat_4_value=0&vat_5_net=0&vat_5_value=0&vat_6_net=0&vat_6_value=0&vat_7_net=0&vat_7_value=0&vat_8_net=0&vat_8_value=0&payment_mode=3&discount=200&total_gross=9562";
$plaintext = $data;
//define('CRYPT_RSA_PKCS15_COMPAT', true);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = base64_encode(strrev($rsa->encrypt($plaintext)));
echo "data";
echo $ciphertext; // there is encoded value getting
and
then how to decrypt encrypted data using private key:
echo $rsa->decrypt($ciphertext); // this is giving error , decryption error
actually , i want to encrypt in php and decrypt in c# ,
data encrypted successfully and when c# rsa crypto service decrypt this encrypted data then giving error message : invalid base-64 string length
$public_key_xml and $private_key_xml is defined below...
public key :
<RSAKeyValue>
<Modulus>uidt3bPfWozkIkC6nHnRDbXrvjqplfCslV2zP4hKJ6sVjVnPfjMM0ueCuEDFZ9NK+kCWaPNAVhOKKwL8HmoX/7KcFLWkwSoatnrncHTH5STey+bqR1xTFY+Rubj8BZt7D9JJYyLQC46wn4ySVnLWkCZZ9+aaTriEBzGTpUzeRiUTWVprp3oXsA7ZKyn+lhZfMx1ILhcD8dnX7xFHB57jIKvPBxAdT4K7GxdgENeS76I/zmVmlF//JnmtZ/RM1WmRkx8mFmcK/Ky8gLsmIpPPltoyBWIKIf2NQH9kHqHa2gwoPg34LTutV9AACTWuiVOjqU7Gq2BHQcjovXMF8t3Wiw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
private key :
<RSAKeyValue>
<Modulus>uidt3bPfWozkIkC6nHnRDbXrvjqplfCslV2zP4hKJ6sVjVnPfjMM0ueCuEDFZ9NK+kCWaPNAVhOKKwL8HmoX/7KcFLWkwSoatnrncHTH5STey+bqR1xTFY+Rubj8BZt7D9JJYyLQC46wn4ySVnLWkCZZ9+aaTriEBzGTpUzeRiUTWVprp3oXsA7ZKyn+lhZfMx1ILhcD8dnX7xFHB57jIKvPBxAdT4K7GxdgENeS76I/zmVmlF//JnmtZ/RM1WmRkx8mFmcK/Ky8gLsmIpPPltoyBWIKIf2NQH9kHqHa2gwoPg34LTutV9AACTWuiVOjqU7Gq2BHQcjovXMF8t3Wiw==</Modulus><Exponent>AQAB</Exponent><P>9NiLuI9TjNvpAPQqD9ySdMX37OmEDCF02isoovt8hwPpiXcZYH4FeasNZoydRrBUOHTTRrW3xdUYGsCZ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RkT3948fC5KDvE0KetYDsrVApRSKzvBUQCVNmcO2o+rhMO1qKvS+zkw2VW5OxGDk/QuHuXIkCyipUEMa/DmK74hoxCaQ==</D></RSAKeyValue>
You must be using a really old version of phpseclib since phpseclib has had built in support for the XML format for quite a few years. So my first recommendation would be to upgrade to the latest version. After that you should be able to do something like this:
<?php
include('Crypt/RSA.php');
$plaintext = 'zzz';
$rsa = new Crypt_RSA();
$rsa->loadKey('<RSAKeyValue>
<Modulus>uidt3bPfWozkIkC6nHnRDbXrvjqplfCslV2zP4hKJ6sVjVnPfjMM0ueCuEDFZ9NK+kCWaPNAVhOKKwL8HmoX/7KcFLWkwSoatnrncHTH5STey+bqR1xTFY+Rubj8BZt7D9JJYyLQC46wn4ySVnLWkCZZ9+aaTriEBzGTpUzeRiUTWVprp3oXsA7ZKyn+lhZfMx1ILhcD8dnX7xFHB57jIKvPBxAdT4K7GxdgENeS76I/zmVmlF//JnmtZ/RM1WmRkx8mFmcK/Ky8gLsmIpPPltoyBWIKIf2NQH9kHqHa2gwoPg34LTutV9AACTWuiVOjqU7Gq2BHQcjovXMF8t3Wiw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>');
define('CRYPT_RSA_PKCS15_COMPAT', true);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
echo base64_encode($rsa->encrypt($plaintext));
If that doesn't work it'd help to see the .NET code you're using to decrypt. Also, if you could encrypt a string in .NET and post the public key you used to do the encryption and the ciphertext itself that'd be useful. From that I could play around with the phpseclib options until I found some combination of options that let me decrypt the string, which would, presumably, in turn, give us insight in how to encrypt the string.

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.

Categories