Tuesday, January 09, 2018

RSA encryption between Java and PHP

This article shows you one way to get RSA encryption working between Java and PHP without any extra libraries or classes, you only need the openssl module activated on PHP side.
The goal is to encrypt a text with a public key in Java and send the code to PHP where it is decoded with the private key.
It took me two days and a lot of googling to figure this out, and I hope this will help others not to spend so much time on this topic.
1) Install and Configure PHP OpenSSL (Windows)
  • php.ini: extension=php_openssl.dll
  • Set environment variable  
    OPENSSL_CONF to C:\Programme\Apache2.2\php\extras\openssl\openssl.cnf
  • Set environment variable  
    PATH to C:\Programme\Apache2.2\php
2) Generate a private keyfile with PHP
1
2
3
$keys = openssl_pkey_new();
$priv = openssl_pkey_get_private($keys);
openssl_pkey_export_to_file($priv, 'private.pem');
3) Generate a public .der-file from the private keyfile with OpenSSL
  • openssl rsa -in private.pem -pubout -outform DER -out public.der
4) Import the public key in Java
1
2
3
4
5
6
7
8
9
10
File pubKeyFile = new File("public.der");
DataInputStream dis = new DataInputStream(new FileInputStream(pubKeyFile));
byte[] keyBytes = new byte[(int) pubKeyFile.length()];
 
dis.readFully(keyBytes);
dis.close();
 
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKey publicKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);
5) Encode the data in Java with the public key
1
2
3
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encrypted = cipher.doFinal(text.getBytes());
6) Decode the data with the private key in PHP
$fp = fopen(“private.pem”, “r”);
$privateKey = fread($fp, 8192);
fclose($fp);
$res = openssl_get_privatekey($privateKey);
openssl_private_decrypt($this->hex2bin($params[‘cipher’]), $decrypted, $res);
// $decrypted is the result
function hex2bin($hexdata) {
$bindata = “”;
for ($i = 0; $i < strlen($hexdata); $i += 2) { $bindata .= chr(hexdec(substr($hexdata, $i, 2))); } return $bindata; } [/sourcecode] 7) If you want to decrypt with the public key in PHP as well, you can generate a public.pem file with OpenSSL
  • openssl rsa -in private.pem -out public.pem -outform PEM -puboutr
Original Post URL: https://schneimi.wordpress.com/2008/11/25/rsa-encryption-between-java-and-php/

Tuesday, October 24, 2017

Launch iOS app without using Storyboard



1. Create your own ViewController in your application
2. Add @property (strong, nonatomic) UINavigationController *navController in your AppDelegate.h
3. Add the following codes inside 'didFinishLaunchingWithOptions'
   UIViewController *viewController = [[YourVC alloc] init];
OR 
   [[NSClassFromString(@"YourVC") alloc] initWithNibName:@"YourVC" bundle:nil];


    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    self.navController = [[UINavigationController alloc] initWithRootViewController:viewController];
    self.navController.navigationBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [self.window setRootViewController:self.navController];
    
    [UIApplication sharedApplication].statusBarHidden = YES; // If needed
    [self.window makeKeyAndVisible];
    return YES;

Tuesday, July 14, 2015

TripleDES Encryption and Decryption using Android and .NET

Here we using the TripleDES Encryption and Decryption code in Android

import org.apache.commons.codec.binary.Base64;

import java.security.MessageDigest;
import java.security.spec.KeySpec;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

public class TripleDES {

    String secretKey = "YOUR_KEY";
    public String _encrypt(String message) throws Exception {

        MessageDigest md = MessageDigest.getInstance("md5");
        byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
        byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);

        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        KeySpec keySpec = new DESedeKeySpec(keyBytes);
        SecretKey key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance("DESede");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte[] plainTextBytes = message.getBytes("utf-8");
        byte[] buf = cipher.doFinal(plainTextBytes);
        byte[] base64Bytes = Base64.encodeBase64(buf);
        String base64EncryptedString = new String(base64Bytes);

        return base64EncryptedString;
    }

    public String _decrypt(String encryptedText) throws Exception {

        byte[] message = Base64.decodeBase64(encryptedText.getBytes("utf-8"));

        MessageDigest md = MessageDigest.getInstance("md5");
        byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
        byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        KeySpec keySpec = new DESedeKeySpec(keyBytes);
        SecretKey key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);

        Cipher decipher = Cipher.getInstance("DESede");
        decipher.init(Cipher.DECRYPT_MODE, key);

        byte[] plainText = decipher.doFinal(message);

        String result = new String(plainText, "UTF-8");

        return result;
    }

}



Then we using the same in .NET like this

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Security.Cryptography;
using System.Text;

public class CryptorEngine
    {
        /// <summary>
        /// Encrypt a string using dual encryption method. Return a encrypted cipher Text
        /// </summary>
        /// <param name="toEncrypt">string to be encrypted</param>
        /// <param name="useHashing">use hashing? send to for extra secirity</param>
        /// <returns></returns>
        /// 

        static string key = "YOUR_KEY";
         
        public static string Encrypt(string toEncrypt, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
            // Get the key from config file
            //string key = "YOUR_KEY";// (string)settingsReader.GetValue("SecurityKey", typeof(String));
            //System.Windows.Forms.MessageBox.Show(key);
            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd5.Clear();
            }
            else
                keyArray = UTF8Encoding.UTF8.GetBytes(key);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tdes.Clear();
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        /// <summary>
        /// DeCrypt a string using dual encryption method. Return a DeCrypted clear string
        /// </summary>
        /// <param name="cipherString">encrypted string</param>
        /// <param name="useHashing">Did you use hashing to encrypt this data? pass true is yes</param>
        /// <returns></returns>
        public static string Decrypt(string cipherString, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = Convert.FromBase64String(cipherString);

            System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
            //Get your key from config file to open the lock!
            //string key = "YOUR_KEY"; //(string)settingsReader.GetValue("SecurityKey", typeof(String));

            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd5.Clear();
            }
            else
                keyArray = UTF8Encoding.UTF8.GetBytes(key);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            tdes.Clear();
            return UTF8Encoding.UTF8.GetString(resultArray);
        }
    }