Decrypting Error in Openssl using PHP - php

I send an encrypted base64 encoded JSON object
N4m4EBDjdCfq5V1JqjMXdO6PEjNEh1fAMaHPn....
to an API which reads and returns a response , I am facing trouble trying to decrypt the response. The response I get from the API is
� �Gֲ:й�#���BJ)3ࣗ�%���wW��u~��J�1��(�/�ik�A���Ԥ& ��g��yi�ُ�3��qxQ������4iM���k�o��k����k\�6�x9
My code for Decryption
$private_key = file_get_contents('privateKey.key');
$res = openssl_pkey_get_private($private_key);
$a_key = openssl_pkey_get_details($res);
// Decrypt the data in the small chunks
$chunkSize = ceil($a_key['bits'] / 8);
$output = '';
while ($response)
{
$chunk = substr($response, 0, $chunkSize);
$response = substr($response, $chunkSize);
$decrypted = '';
if (!openssl_private_decrypt($chunk, $decrypted, $res, OPENSSL_NO_PADDING))
{
while ($msg = openssl_error_string())
echo $msg . "<br />\n";
}
$output .= $decrypted;
}
openssl_free_key($res);
echo '<br /><br /> Unencrypted Data: ' .$output;
The output after decryption is
�E�X,�/�၏�����2#>�o����� 1f�=�*�O���г���18}Yi�,�_�ڪ�|
but I am expecting a readable plain text response.
EDIT : I now understand that the encryption is happening at one end in Java, the sample code for encryption is
The code for using .pem file below:
public static String encrypt(String rawText, PublicKey publicKey) throws
IOException, GeneralSecurityException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.encodeBase64String(cipher.doFinal(rawText.getBytes("UTF-
8")));
}
public static RSAPublicKey getPublicKey(String filename) throws IOException,
GeneralSecurityException {
String publicKeyPEM = getKey(filename);
return getPublicKeyFromString(publicKeyPEM);
}
public static RSAPublicKey getPublicKeyFromString(String key) throws
IOException, GeneralSecurityException {
String publicKeyPEM = key;
publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
byte[] encoded = Base64.decodeBase64(publicKeyPEM);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(new
X509EncodedKeySpec(encoded));
return pubKey;
}
private static String getKey(String filename) throws IOException {
// Read key from file
String strKeyPEM = "";
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
while ((line = br.readLine()) != null) {
strKeyPEM += line + "\n";
}
br.close();
return strKeyPEM;
}
public static void main(String[] args) {
RSA necryptionService = new RSA();
try
{
String file = "D:/public.pem";
String data = "Hello Test"
PublicKey publicKey = necryptionService.getPublicKey(file);
String encryptedData = necryptionService.encrypt(data,publicKey);
System.out.println(encryptedData);
}
catch (Exception e)
{
e.printStackTrace();
}
}
Where the string gets converted in the 3rd method, try this additional piece
of code
CertificateFactory fact = CertificateFactory.getInstance("X.509");
FileInputStream is = new FileInputStream(path);
Certificate cer = fact.generateCertificate(is);
logger.info("Public Key:::::::::::loaded"+cer.getPublicKey());
I send my request to the API using cURL and get back the java encrypted response.
The encrypted request is
Zxh5xmxS6pteaq+aWWorF7WRGPn6MB5SlcUR16ncYbUPaNfhOiHskYPuxY+6I3KoHLGWpZ3IndTkaS0CxOSNwFFIsLcAWj9Jv9B6rnk8Y0Tt54d4fygfpY0FGUJdxlgY7DN0ll00OBMqlcReWlBoVxWP06nHLuUmNke9SH0ToJo+V/S7ntQYTBYV+DVbFLJF+/U7woM6xHY8pSoBfKFC1r443ftOP05adkUcrPVIrvswIfk+4TmRvF5Th1tKaHQyGCQ6MJnOZt37RIiMFnfyqgC7RUQHnz6CfnfXKqe3RCUiuZ0wuRaPPLLzmbBhh0Qi7egJqmvFWl6Mx177a3cseVSikhI50QxRnl2zQjcUcUBWXvLf2av+ggBrSb2rLr4+3B2MGUV/5831LH4jDYuLhhYteeq36vODiEE6io/WxOr/V8LCDe44kOoJiKIe0agghGWBVmsEaMAKHLnDKrA885RAEf1ogtXwPlKaMWHD3QCOAWttH2TlRCwzdNLdMr4lrsHUR5CLceQt8zPSSfo9eP6EvvO6HbEfvd2ynbqxEaOlkCrGcQKvMXcSQ0/pefq6LEx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03hcFVu/375HE2S5lYbgAQZ2NzXVua6WF
t2rnTjk2EmPjV8Byg7o4Xt7Op5c21reIOuAfh8OQc1m6zqJ8LDiMJ5Cd7eiW2w==
-----END RSA PRIVATE KEY-----

Related

how to convert java code to php?

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

encrypt/decrypt with Android and PHP

Sorry for this question. I've read all the previous questions, but my code still not work.
Thanks in advance to anyone that will help me in understanding where is the problem.
In android I use this code for reading the public key and produce the encrypted text:
public static PublicKey getPublicKeyFromString(String stringKey) throws Exception {
byte[] keyBytes = stringKey.getBytes();
byte[] decode = Base64.decode(keyBytes, Base64.DEFAULT);
KeyFactory fact = KeyFactory.getInstance("RSA");
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(decode);
return (PublicKey) fact.generatePublic(x509KeySpec);
}
public static String RSAEncrypt(final String plain, final PublicKey publicKey)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
byte[] encryptedBytes;
Cipher cipher;
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plain.getBytes());
return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
}
//I call these functions in this manner.
private final String pubKeyString =
//"-----BEGIN PUBLIC KEY-----" +
"MIG..." +
"...";
//"-----END PUBLIC KEY-----"
PublicKey pubKey = RSAFunctions.getPublicKeyFromString(pubKeyString);
String encData = RSAFunctions.RSAEncrypt("prova", pubKey);
The publickey.php and privatekey.php file are generated in php with this code:
<?php
include('./Crypt/RSA.php');
$rsa = new Crypt_RSA();
extract($rsa->createKey()); // == $rsa->createKey(1024) where 1024 is the key size
$File1 = "./privatekey.php";
$Handle = fopen($File1, 'w');
fwrite($Handle, "<?php \$privatekey=\"" . $privatekey . "\"?>");
fclose($Handle);
$File2 = "./publickey.php";
$Handle = fopen($File2, 'w');
fwrite($Handle, "<?php \$publickey=\"" . $publickey . "\"?>");
fclose($Handle);
?>
In php I use this code for decrypt data:
<?php
include('Crypt/RSA.php');
require('privatekey.php');
$rsa = new Crypt_RSA();
$rsa->loadKey($privatekey); // private key
$base64_string = $_GET["data"];
$base64_string = str_replace(' ', '+', $base64_string);
$ciphertext = base64_decode( $base64_string );
//$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$plaintext = $rsa->decrypt($ciphertext);
echo $plaintext;
?>
I've also made a php crypt script for testing my decrypt php function. This is the code of my encrypt.php:
<?php
include('Crypt/RSA.php');
require('publickey.php');
$rsa = new Crypt_RSA();
$rsa->loadKey($publickey); // public key
$plaintext = $_GET["data"];
//$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$ciphertext = $rsa->encrypt($plaintext);
echo base64_encode( $ciphertext );
?>
I've no problem when encrypt and decrypt text using only php, but if I use the encrypted data made with android app, php give me an error in decrypting.
Thanks for the attention.
In your php there is :
CRYPT_RSA_ENCRYPTION_PKCS1
but when you create your Cipher object on Android you omit the mode and padding
cipher = Cipher.getInstance("RSA");
you should try something like
Cipher c = Cipher.getInstance("AES/CBC/PKCS1Padding");
ref :
http://developer.android.com/reference/javax/crypto/Cipher.html

PHP decrypting data with RSA Private Key

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)

openssl_public_decrypt returns false but cannot get error message

I'm trying to decode a string that was encoded with RSA private key at an Android device (as some kind of digital signature). I think I have a problem with my public key at server side.
if (openssl_public_decrypt($token, $decrypted, $pubKey) == FALSE)
{
while ($msg = openssl_error_string())
{
echo "ERROR: " . $msg;
}
return;
}
The function openssl_public_decrypt() returns false but openssl_error_string() does not return any errors. How can I find out what is going wrong here?
UPDATE:
This is how I create the encoded value in Android:
public static String Sign(byte[] text, RSAPrivateKey privateKey) throws Exception
{
// Encode the original data with RSA private key
byte[] encodedBytes = null;
try {
Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c.init(Cipher.ENCRYPT_MODE, privateKey);
encodedBytes = c.doFinal(text);
} catch (Exception e) {
Log.e("RSAHelper", "RSA encryption error");
throw e;
}
return Base64.encodeToString(encodedBytes, Base64.DEFAULT);
}
I'm trying to decode a string that was encoded with RSA private key at an Android device (as some kind of digital signature)
If its a digital signature, then the padding scheme is different. RSA encryption uses Type 2 padding, while RSA signatures uses Type 1 padding.
Since you believe its a digital signature, you should probably look for a openssl_public_verify function (or similar).
I didn't really find out why openssl_error_string() returns nothing but I could solve my problem with the not accepted PublicKey
Since the key-pair had been created by Android it could not be directly used by PHP. The following problems needed to be solved:
Missing header and footer
Wrong line breaks
// remove existing line breaks
$pubKey = str_replace ("\r\n" , "" , $pubKey);
$pubKey = str_replace ("\r" , "" , $pubKey);
$pubKey = str_replace ("\n" , "" , $pubKey);
// insert line breaks as expexted by PHP function
$pubKey = wordwrap($pubKey, 65, "\n", true);
// add header and footer
$pubKeyWithHeader = "-----BEGIN PUBLIC KEY----- \r\n" . $pubKey
. " \r\n-----END PUBLIC KEY-----";
// decode the key
openssl_pkey_get_public($pubKeyWithHeader);
if ($x == FALSE)
{
echo "error";
return;
}
// decrypt the message with the public key
if (openssl_public_decrypt($token, $decrypted, $pubKeyWithHeader) == FALSE)
{
echo "error";
return;
}
echo $decrypted;

Encrypt in VB.NET and Decrypt in PHP

I am trying to write a function in PHP and in VB.NET that uses Triple DES to pass in BOTH directions encrypted data. The problem, is that when I try to decrypt a string encrypted in VB.NET using PHP, I get an error message saying that the block size of the IV must match.
The class I wrote in VB.NET, is as follows and is fully functional as it will encrypt and decrypt its own blocks flawlessly.
Imports System
Imports System.Text
Imports System.IO
Imports System.Security.Cryptography
Public Class Cipher
Dim method As TripleDESCryptoServiceProvider
Dim key As Byte()
Public Property Password() As String
Get
Return System.Text.Encoding.Unicode.GetString(Key)
End Get
Set(value As String)
key = System.Text.Encoding.Unicode.GetBytes(value)
End Set
End Property
Public Function Encrypt(data As String) As String
Dim ms As New System.IO.MemoryStream
' Create the encoder to write to the stream.
Dim dataBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(data)
Dim encStream As New CryptoStream(ms, method.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
' Use the crypto stream to write the byte array to the stream.
encStream.Write(dataBytes, 0, dataBytes.Length)
encStream.FlushFinalBlock()
' IV and Ciphered string are each Base64'd and seperated by a comma, then the whole result is Base64'd
Return Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(Convert.ToBase64String(method.IV) & "," & Convert.ToBase64String(ms.ToArray)))
End Function
Public Function Decrypt(data As String) As String
' Convert the encrypted text string to a byte array.
Dim partDecoded As String = System.Text.Encoding.Unicode.GetString(Convert.FromBase64String(data))
Dim dataBytes() As Byte
If InStr(partDecoded, ",") > 0 Then
Dim parts() As String = Split(partDecoded, ",")
' Get IV from first part
method.IV = Convert.FromBase64String(parts(0))
' Get ciphered data from second part
dataBytes = Convert.FromBase64String(parts(1))
' Create the stream.
Dim ms As New System.IO.MemoryStream
' Create the decoder to write to the stream.
Dim decStream As New CryptoStream(ms, method.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
' Use the crypto stream to write the byte array to the stream.
decStream.Write(dataBytes, 0, dataBytes.Length)
decStream.FlushFinalBlock()
' Convert the plaintext stream to a string.
Return System.Text.Encoding.Unicode.GetString(ms.ToArray)
Else
Return False
End If
End Function
Public Sub New()
method = New TripleDESCryptoServiceProvider
method.Mode = CipherMode.CFB
method.GenerateIV()
End Sub
End Class
Example usage of the above class
Dim c As New Cipher
c.Password = "12345"
Dim encrypted As String = c.Encrypt("hello")
Debug.Print(encrypted)
Dim decrypted As String = c.Decrypt(encrypted)
Debug.Print(decrypted)
Now I also have the following PHP code which ALSO works (by itself)
class Cipher {
private $iv;
private $securekey;
function __construct($key) {
$this->securekey = $key;
}
function encrypt($string) {
$this->iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_CFB),MCRYPT_DEV_RANDOM);
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_3DES, $this->securekey, $string, MCRYPT_MODE_CFB, $this->iv));
return base64_encode(base64_encode($this->iv) . ',' . $encrypted);
}
function decrypt($string) {
$decrypt = base64_decode($string);
if(strpos($decrypt,',') > 0) {
$decrypt = explode(',', $decrypt);
$this->iv = base64_decode($decrypt[0]);
return trim(mcrypt_decrypt(MCRYPT_3DES, $this->securekey, base64_decode($decrypt[1]), MCRYPT_MODE_CFB, $this->iv));
} else {
return false;
}
}
}
PHP Example Usage
$c = new Cipher("12345");
$encrypted = $c->encrypt("hello");
echo 'Encrypted: ' . $encrypted . '<br />';
$decrypted = $c->decrypt($encrypted);
echo 'Decrypted: ' . $decrypted . '<br />';
$vb = "MwBOAEoAOQBjAEgAcQAyAC8ASABzAD0ALABmAEUAOQBaAHYAVwBzAFUAYQB3AFYARwBGAHUANABLAGUAVgB3AFcAaABRAD0APQA=";
echo 'VB.NET Dec: ' . $c->decrypt($vb);
What I have included above in the PHP usage, is the Base64 string made with VB.NET that decodes PERFECTLY in VB.NET as the variable $vb.
This is driving me absolutely batty, as the code is correct, and functional -- in both cases -- so what am I missing and can you point out / fix the problem. I do not wish to use Rijndael, or explore other cipher methods, as this one is well established that works across multiple devices natively (iOS, Android, Windows, Linux, etc.).
Since no one was able to provide a fully functional BI-DIRECTIONAL solution, I have taken the liberty to provide one for the community on this article.
The problem, is that PHP does not conform to the standards by forcing the strings to be padded in order to match. Presently, there is no known way to reliably pass the IV if randomly generated between .NET and PHP (if you do discover how, or this changes, please feel free to revise this).
Following is the COMPLETE solution for encrypting data using Triple DES in a manner that is compatible with .NET and PHP which allows for bi-directional Triple DES encrypted communication. This method is also compatible with Java, Delphi, Objective-C, and many other languages, however such code is not going to be supplied here as that is not a solution to the posted question.
VB.NET Triple DES Class
Imports System
Imports System.Text
Imports System.IO
Imports System.Security.Cryptography
Public Class TripleDES
Private bPassword As Byte()
Private sPassword As String
Public Sub New(Optional ByVal Password As String = "password")
' On Class Begin
Me.Password = Password
End Sub
Public ReadOnly Property PasswordHash As String
Get
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Return UTF8.GetString(bPassword)
End Get
End Property
Public Property Password() As String
Get
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Return sPassword
End Get
Set(value As String)
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Dim HashProvider As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
bPassword = HashProvider.ComputeHash(UTF8.GetBytes(value))
sPassword = value
End Set
End Property
#Region "Encrypt"
' Encrypt using Password from Property Set (pre-hashed)
Public Function Encrypt(ByVal Message As String) As String
Dim Results() As Byte
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Using HashProvider As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim TDESKey() As Byte = bPassword
Using TDESAlgorithm As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() With {.Key = TDESKey, .Mode = CipherMode.ECB, .Padding = PaddingMode.PKCS7}
Dim DataToEncrypt() As Byte = UTF8.GetBytes(Message)
Try
Dim Encryptor As ICryptoTransform = TDESAlgorithm.CreateEncryptor
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length)
Finally
TDESAlgorithm.Clear()
HashProvider.Clear()
End Try
End Using
End Using
Return Convert.ToBase64String(Results)
End Function
' Encrypt using Password as byte array
Private Function Encrypt(ByVal Message As String, ByVal Password() As Byte) As String
Dim Results() As Byte
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Using HashProvider As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim TDESKey() As Byte = HashProvider.ComputeHash(UTF8.GetBytes(UTF8.GetString(Password)))
Using TDESAlgorithm As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() With {.Key = TDESKey, .Mode = CipherMode.ECB, .Padding = PaddingMode.PKCS7}
Dim DataToEncrypt() As Byte = UTF8.GetBytes(Message)
Try
Dim Encryptor As ICryptoTransform = TDESAlgorithm.CreateEncryptor
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length)
Finally
TDESAlgorithm.Clear()
HashProvider.Clear()
End Try
End Using
End Using
Return Convert.ToBase64String(Results)
End Function
' Encrypt using Password as string
Public Function Encrypt(ByVal Message As String, ByVal Password As String) As String
Dim Results() As Byte
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
' Step 1. We hash the Passphrase using MD5
' We use the MD5 hash generator as the result is a 128 bit byte array
' which is a valid length for the Triple DES encoder we use below
Using HashProvider As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim TDESKey() As Byte = HashProvider.ComputeHash(UTF8.GetBytes(Password))
' Step 2. Create a new TripleDESCryptoServiceProvider object
' Step 3. Setup the encoder
Using TDESAlgorithm As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() With {.Key = TDESKey, .Mode = CipherMode.ECB, .Padding = PaddingMode.PKCS7}
' Step 4. Convert the input string to a byte[]
Dim DataToEncrypt() As Byte = UTF8.GetBytes(Message)
' Step 5. Attempt to encrypt the string
Try
Dim Encryptor As ICryptoTransform = TDESAlgorithm.CreateEncryptor
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length)
Finally
' Clear the Triple Des and Hashprovider services of any sensitive information
TDESAlgorithm.Clear()
HashProvider.Clear()
End Try
End Using
End Using
' Step 6. Return the encrypted string as a base64 encoded string
Return Convert.ToBase64String(Results)
End Function
#End Region
#Region "Decrypt"
' Decrypt using Password from Property (pre-hashed)
Public Function Decrypt(ByVal Message As String) As String
Dim Results() As Byte
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Using HashProvider As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim TDESKey() As Byte = Me.bPassword
Using TDESAlgorithm As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() With {.Key = TDESKey, .Mode = CipherMode.ECB, .Padding = PaddingMode.PKCS7}
Dim DataToDecrypt() As Byte = Convert.FromBase64String(Message)
Try
Dim Decryptor As ICryptoTransform = TDESAlgorithm.CreateDecryptor
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length)
Finally
TDESAlgorithm.Clear()
HashProvider.Clear()
End Try
End Using
End Using
Return UTF8.GetString(Results)
End Function
' Decrypt using Password as Byte array
Public Function Decrypt(ByVal Message As String, ByVal Password() As Byte) As String
Dim Results() As Byte
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Using HashProvider As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim TDESKey() As Byte = HashProvider.ComputeHash(UTF8.GetBytes(UTF8.GetString(Password)))
Using TDESAlgorithm As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() With {.Key = TDESKey, .Mode = CipherMode.ECB, .Padding = PaddingMode.PKCS7}
Dim DataToDecrypt() As Byte = Convert.FromBase64String(Message)
Try
Dim Decryptor As ICryptoTransform = TDESAlgorithm.CreateDecryptor
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length)
Finally
TDESAlgorithm.Clear()
HashProvider.Clear()
End Try
End Using
End Using
Return UTF8.GetString(Results)
End Function
' Decrypt using Password as string
Public Function Decrypt(ByVal Message As String, ByVal Password As String) As String
Dim Results() As Byte
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
' Step 1. We hash the pass phrase using MD5
' We use the MD5 hash generator as the result is a 128-bit byte array
' which is a valid length for the Triple DES encoder we use below
Using HashProvider As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim TDESKey() As Byte = HashProvider.ComputeHash(UTF8.GetBytes(Password))
' Step 2. Create a new TripleDESCryptoServiceProvider object
' Step 3. Setup the decoder
Using TDESAlgorithm As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() With {.Key = TDESKey, .Mode = CipherMode.ECB, .Padding = PaddingMode.PKCS7}
' Step 4. Convert the input string to a byte[]
Dim DataToDecrypt() As Byte = Convert.FromBase64String(Message)
' Step 5. Attempt to decrypt the string
Try
Dim Decryptor As ICryptoTransform = TDESAlgorithm.CreateDecryptor
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length)
Finally
' Clear the Triple Des and Hash provider services of any sensitive information
TDESAlgorithm.Clear()
HashProvider.Clear()
End Try
End Using
End Using
' Step 6. Return the decrypted string in UTF8 format
Return UTF8.GetString(Results)
End Function
#End Region
End Class
VB.NET Triple DES Class Usage
Dim tdes As New TripleDES("12345")
Dim vbEncrypted = tdes.Encrypt("Encrypted using VB.NET")
Dim phpEncrypted = "5Ittyr0+jiI7QQmPrvSVnMc9MEWQCjAN"
Debug.Print("PHP Encrypted: " & phpEncrypted)
Debug.Print("VB Encrypted: " & vbEncrypted)
Debug.Print("PHP Encrypted (decrypted result): " & tdes.Decrypt(phpEncrypted))
Debug.Print("VB Encrypted (decrypted result): " & tdes.Decrypt(vbEncrypted))
PHP Triple DES Class
class TripleDES {
private $bPassword;
private $sPassword;
function __construct($Password) {
$this->bPassword = md5(utf8_encode($Password),TRUE);
$this->bPassword .= substr($this->bPassword,0,8);
$this->sPassword - $Password;
}
function Password($Password = "") {
if($Password == "") {
return $this->sPassword;
} else {
$this->bPassword = md5(utf8_encode($Password),TRUE);
$this->bPassword .= substr($this->bPassword,0,8);
$this->sPassword - $Password;
}
}
function PasswordHash() {
return $this->bPassword;
}
function Encrypt($Message, $Password = "") {
if($Password <> "") { $this->Password($Password); }
$size=mcrypt_get_block_size('tripledes','ecb');
$padding=$size-((strlen($Message)) % $size);
$Message .= str_repeat(chr($padding),$padding);
$encrypt = mcrypt_encrypt('tripledes',$this->bPassword,$Message,'ecb');
return base64_encode($encrypt);
}
function Decrypt($message, $Password = "") {
if($Password <> "") { $this->Password($Password); }
return trim(mcrypt_decrypt('tripledes', $this->bPassword, base64_decode($message), 'ecb'), ord(2));
}
}
PHP Triple DES Class Usage
$tdes = new TripleDES("12345");
$phpEncrypted = $tdes->encrypt("Encrypted using PHP");
$vbEncrypted = "5Ittyr0+jiI7QQmPrvSVnP3s2CeoTJmF"; // Encrypted using VB.NET
echo "PHP Encrypted: " . $phpEncrypted . '<br />';
echo "VB Encrypted: " . $vbEncrypted . '<br />';
echo "PHP Encrypted (decrypted result): " . $tdes->Decrypt($phpEncrypted) . '<br />';
echo "VB Encrypted (decrypted result): " . $tdes->Decrypt($vbEncrypted) . '<br />';
I did what I could to make both classes usability level identical as the languages would allow naturally. Since PHP does not allow overloading functions, I had to use the password as an optional parameter, which is a string value. The VB.NET solution has an additional override that allows you to pass the byte value of the password string on encrypt/decrypt functions. The example code provided to show the usage for each, shows the most simplistic form of instantiating the object which both classes allow for setting the password on object creation.
For anyone else out there that was bashing their brains trying to find a WORKING bi-directional solution for Triple DES (and did not want to be forced into the box that everyone seems to be pointing to -- Rijndael), then this solution is for you, and you can stop banging your head against the wall.
Added a C# translation of the VB.NET TripleDES class
C# Class ( Added [2017-01-11] )
using System;
using System.Security.Cryptography;
public class TripleDES {
private byte[] bPassword;
private string sPassword;
public TripleDES( string Password = "password" ) {
// On Class Begin
this.Password = Password;
}
public string PasswordHash {
get {
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
return UTF8.GetString( bPassword );
}
}
public string Password {
get {
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
return sPassword;
}
set {
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
bPassword = HashProvider.ComputeHash( UTF8.GetBytes( value ) );
sPassword = value;
}
}
#region "Encrypt"
// Encrypt using Password from Property Set (pre-hashed)
public string Encrypt( string Message ) {
byte[] Results = null;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
using ( MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider() ) {
byte[] TDESKey = bPassword;
using ( TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider { Key = TDESKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 } ) {
byte[] DataToEncrypt = UTF8.GetBytes( Message );
try {
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock( DataToEncrypt, 0, DataToEncrypt.Length );
} finally {
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
return Convert.ToBase64String( Results );
}
// Encrypt using Password as byte array
private string Encrypt( string Message, byte[] Password ) {
byte[] Results = null;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
using ( MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider() ) {
byte[] TDESKey = HashProvider.ComputeHash( UTF8.GetBytes( UTF8.GetString( Password ) ) );
using ( TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider { Key = TDESKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 } ) {
byte[] DataToEncrypt = UTF8.GetBytes( Message );
try {
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock( DataToEncrypt, 0, DataToEncrypt.Length );
} finally {
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
return Convert.ToBase64String( Results );
}
// Encrypt using Password as string
public string Encrypt( string Message, string Password ) {
byte[] Results = null;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
// Step 1. We hash the Passphrase using MD5
// We use the MD5 hash generator as the result is a 128 bit byte array
// which is a valid length for the Triple DES encoder we use below
using ( MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider() ) {
byte[] TDESKey = HashProvider.ComputeHash( UTF8.GetBytes( Password ) );
// Step 2. Create a new TripleDESCryptoServiceProvider object
// Step 3. Setup the encoder
using ( TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider { Key = TDESKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 } ) {
// Step 4. Convert the input string to a byte[]
byte[] DataToEncrypt = UTF8.GetBytes( Message );
// Step 5. Attempt to encrypt the string
try {
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock( DataToEncrypt, 0, DataToEncrypt.Length );
} finally {
// Clear the Triple Des and Hashprovider services of any sensitive information
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
// Step 6. Return the encrypted string as a base64 encoded string
return Convert.ToBase64String( Results );
}
#endregion
#region "Decrypt"
// Decrypt using Password from Property (pre-hashed)
public string Decrypt( string Message ) {
byte[] Results = null;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
using ( MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider() ) {
byte[] TDESKey = this.bPassword;
using ( TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider { Key = TDESKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 } ) {
byte[] DataToDecrypt = Convert.FromBase64String( Message );
try {
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock( DataToDecrypt, 0, DataToDecrypt.Length );
} finally {
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
return UTF8.GetString( Results );
}
// Decrypt using Password as Byte array
public string Decrypt( string Message, byte[] Password ) {
byte[] Results = null;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
using ( MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider() ) {
byte[] TDESKey = HashProvider.ComputeHash( UTF8.GetBytes( UTF8.GetString( Password ) ) );
using ( TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider { Key = TDESKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 } ) {
byte[] DataToDecrypt = Convert.FromBase64String( Message );
try {
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock( DataToDecrypt, 0, DataToDecrypt.Length );
} finally {
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
return UTF8.GetString( Results );
}
// Decrypt using Password as string
public string Decrypt( string Message, string Password ) {
byte[] Results = null;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
// Step 1. We hash the pass phrase using MD5
// We use the MD5 hash generator as the result is a 128-bit byte array
// which is a valid length for the Triple DES encoder we use below
using ( MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider() ) {
byte[] TDESKey = HashProvider.ComputeHash( UTF8.GetBytes( Password ) );
// Step 2. Create a new TripleDESCryptoServiceProvider object
// Step 3. Setup the decoder
using ( TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider { Key = TDESKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 } ) {
// Step 4. Convert the input string to a byte[]
byte[] DataToDecrypt = Convert.FromBase64String( Message );
// Step 5. Attempt to decrypt the string
try {
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock( DataToDecrypt, 0, DataToDecrypt.Length );
} finally {
// Clear the Triple Des and Hash provider services of any sensitive information
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
// Step 6. Return the decrypted string in UTF8 format
return UTF8.GetString( Results );
}
#endregion
}
For PHP 7+ mccrypt wont work, so here the solution for encrypt and decrypt using the library phpseclib:
$des = new \phpseclib\Crypt\TripleDES(\phpseclib\Crypt\TripleDES::MODE_ECB);
$key = YOURKEY;
$p = md5(utf8_encode($key),TRUE);
$p .= substr($p,0,8);
$p - $key;
$des->setKey($p);
$phpEncrypted = $des->encrypt("Encrypted using PHP");
$vbEncrypted = "5Ittyr0+jiI7QQmPrvSVnP3s2CeoTJmF"; // Encrypted using VB.NET
echo "PHP Encrypted: " . $phpEncrypted . '<br />';
echo "VB Encrypted: " . $vbEncrypted . '<br />';
echo "PHP Encrypted (decrypted result): " . $des->decrypt(base64_decode($phpEncrypted)) . '<br />';
echo "VB Encrypted (decrypted result): " . $des->decrypt(base64_decode($vbEncrypted)) . '<br />';

Categories