Encrypt content with php and java - java

I have an app with java and PHP files. The java files send content to the PHP files, and this one send the response to the java file, by HTTP everything. I have the response with JSON format.
I would like to encrypt the information and decode it in the other side, java->php and php->java(this is the most important) but I don't know how to do it.
Edit:
I am trying BLOWFISH, here is my code in PHP(crypt the data and send to Java) and Java(get the data and decode it)
PHP
$key = "this is the key";
$crypttext = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $result_json, MCRYPT_MODE_ECB);
echo($crypttext);
JAVA
public String decryptBlowfish(String to_decrypt, String strkey) {
System.out.println(to_decrypt);
try {
SecretKeySpec key = new SecretKeySpec(strkey.getBytes(), "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = cipher.doFinal(to_decrypt.getBytes());
return new String(decrypted);
} catch (Exception e) {
System.out.println(e.getMessage());
;
return null;
}
}
System.out.println(decryptBlowfish(result, "this is the key"));
The result when I execute is:
Input length must be multiple of 8 when encrypting with padded cipher
or sometimes
Given final block not properly padded

Agreed with the comment that's what SSL is for see here for a client java application that uses SSL Certificate and encryption to connect to an HTTPS/SSL site: http://www.mkyong.com/java/java-https-client-httpsurlconnection-example/ next you might want to have an HTTPS/SSL php server this should help: http://cweiske.de/tagebuch/ssl-client-certificates.htm Or use this Opensource library: http://nanoweb.si.kz/
If the above fails then I don't know, but a last resort would be writing your own, you may never know how secure it really is?

You might want to use the same algorithm for decoding/decrypting namely "blowfish/ecb/nopadding" instead of "blowfish".
private static final String DECRYPTION_ALGORITHM = "blowfish/ecb/nopadding";
private static final String KEY_ALGORITHM = "blowfish";
private static byte[] decrypt(byte[] keyData, byte[] valueData) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(keyData, KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(DECRYPTION_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
return cipher.doFinal(valueData);
}

If you don't want SSL, which I recommend too, you can try this:
$str = 'hello world'; //your input data
$pass = 'haj83kdj843j'; //something random, the longer the better
$l = strlen($pass);
for ($i=0; $i<strlen($str); $i++)
{
$str[$i] = chr(ord($str[$i]) + ord($pass[$i % $l]));
}
It is fast and easy to write a coder/encoder in any language you want. The resulting string is a binary string so you might want to convert it using base64_encode or something. Should give quite good security.

Related

(Java to Javascript) javax.crypto.Cipher equivalent code in Nodejs Crypto Javascript

I'm trying to convert below java code into nodejs.
private static String TRANS_MODE = "Blowfish";
private static String BLOWFISH_KEY = "BLOWFISH_KEY";
public static String encrypt(String password) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(BLOWFISH_KEY.getBytes("Windows-31J"),TRANS_MODE);
Cipher cipher;
cipher = Cipher.getInstance(TRANS_MODE);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] passByte;
passByte = cipher.doFinal(password.getBytes("Windows-31J"));
return new String(Hex.encodeHex(passByte));
}
Here is what I was able to figure out-
const crypto = require('crypto');
function encrypt(password)
var fcKey = "BLOWFISH_KEY";
var cipher = crypto.createCipher('BF-CBC', fcKey, "");
var encrypted = cipher.update(password,'ascii','hex');
encrypted += cipher.final('hex');
return encrypted;
I'm not able to get same output. For example if
password= "password01"
Java Code output - fe0facbf8d458adaa47c5fe430cbc0ad
Nodejs Code output - ae5e8238c929b5716566e97fa35efb9b
Can someone help me figure out the problem ??
Notice that crypto.createCipher(algorithm, password[, options]) is deprecated and should not be used.
Where the SecretKeySpec(..) in java takes a binary key as input, the createCipher(..) in js takes a "password" as input, and behind the scene tries to derive a binary key using MD5. So your actually key used in the two programs ends up being different. The js methode
also tries to derive an IV from the password, which is bad practice and different from your java code.
In js you need to use the crypto.createCipheriv() instead. And when you are at it, you also need to consider if an iv is needed - both in Java and in js.

decrypting php encrypted data on android

An Android client (4.2.1) application sends a public key via a HttpPost request to a PHP (5.6) API. This API encrypts the data with AES compliant RIJNDAEL_128, then encrypts the key for the AES encryption with the client public key with OpenSSL public encryption and RSA_PKCS1_OAEP_PADDING. It sends this data base64 encoded via XML back to the client android application which shall encrypt the data. I've setup a basic PHP test script which tests the whole process, this works as expected.
Currently I'm working on implementing the decryption in the client Android application but already decrypting the AES-key fails. I have other questions besides this current problem (see at the end).
Here is a text graphical synopsis of what is happening:
client -> public key -> API -> data -> AESencrypt(data), RSAencrypt(AES-key) -> base64encode[AES(data)], base64encode[RSA(AES-key)] -> <xml>base64[AES(data)], base64[RSA(AES-key)]</xml> -> client -> base64[AES(data)], base64[RSA(AES-key)] -> base64decode[AES(data)], base64decode[RSA(AES-key)] -> AESdecrypt(data), RSAdecrypt(AES-key) -> data
I'm encrypting the data with MCRYPT_RIJNDAEL_128 which I read is AES compatible (see PHP doc for mycrypt).
Here is the code:
<?php
$randomBytes = openssl_random_pseudo_bytes(32, $safe);
$randomKey = bin2hex($randomBytes);
$randomKeyPacked = pack('H*', $randomKey);
// test with fixed key:
// $randomKeyPacked = "12345678901234567890123456789012";
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$dataCrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $randomKeyPacked, $data, MCRYPT_MODE_CBC, $iv);
The AES-key coming out of this is encoded with openssl_public_encrypt and the padding setting OPENSSL_PKCS1_OAEP_PADDING. Reading the source code (source of PHP OpenSSL implementation) this is equivalent to RSA_PKCS1_OAEP_PADDING described as
EME-OAEP as defined in PKCS #1 v2.0 with SHA-1, MGF1 and an empty encoding parameter.
in the OpenSSL documentation found here. Afterwards I base64_encode the data to be able to transfer it via an XML string to the client. The code looks like this:
openssl_public_encrypt($randomKeyPacked, $cryptionKeyCrypted, $clientPublicKey, OPENSSL_PKCS1_OAEP_PADDING);
$content = array(
'cryptionKeyCryptedBase64' => base64_encode($cryptionKeyCrypted),
'cryptionIVBase64' => base64_encode($iv),
'dataCryptedBase64' => base64_encode($dataCrypted)
);
// $content gets parsed to a valid xml element here
The client Android application gets the return data via HttpPost request via a BasicResponseHandler. This returned XML string is valid and parsed via Simple to respective java objects. In the the class holding the actual content of the transferred data I currently try to decrypt the data. I decrypt the AES-key with the transformation RSA/ECB/OAEPWithSHA-1AndMGF1Padding which due to this site (only I could find) is a valid string and seems to be the equivalent of the padding I used in PHP. I included the way I generated the private key as it is the same way I generate the public key that was send to the PHP API. Here is that class:
public class Content {
#Element
private String cryptionKeyCryptedBase64;
#Element
private String cryptionIVBase64;
#Element
private String dataCryptedBase64;
#SuppressLint("TrulyRandom")
public String getData() {
String dataDecrypted = null;
try {
PRNGFixes.apply(); // fix TrulyRandom
KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
keygen.initialize(2048);
KeyPair keypair = keygen.generateKeyPair();
PrivateKey privateKey = keypair.getPrivate();
byte[] cryptionKeyCrypted = Base64.decode(cryptionKeyCryptedBase64, Base64.DEFAULT);
//byte[] cryptionIV = Base64.decode(cryptionIVBase64, Base64.DEFAULT);
Cipher cipherRSA = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
cipherRSA.init(Cipher.DECRYPT_MODE, privateKey);
byte[] key = cipherRSA.doFinal(cryptionKeyCrypted);
byte[] dataCrytped = Base64.decode(dataCryptedBase64, Base64.DEFAULT);
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipherAES = Cipher.getInstance("AES");
cipherAES.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decryptedAESBytes = cipherAES.doFinal(dataCrytped);
dataDecrypted = new String(decryptedAESBytes, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return dataDecrypted;
}
}
Doing this I currently fail at line
byte[] key = cipherRSA.doFinal(cryptionKeyCrypted);
with Bad padding exceptions for nearly all PHP openssl_public_encrypt padding parameter - Android Cipher transformation string combinations I tried. Using the standard PHP padding parameter by omitting the padding parameter in the openssl_public_encrypt which defaults to OPENSSL_PKCS1_PADDING and a Cipher transformation string of just Cipher.getInstance("RSA") I do not get a bad padding exception. But the encrypted key seems not to be valid as AES decryption fails with
java.security.InvalidKeyException: Key length not 128/192/256 bits.
I tried validating this with a fixed key (see code comment in PHP code above) and I don't get the same key back after decrypting it and transforming it to a string. It seems it is just garbled data although it is 256 bits long if I read the Eclipse ADT debugger correctly.
What might be the correct Cipher transformation string to use as an equivalent for PHP's OPENSSL_PKCS1_OAEP_PADDING. Reading this documentation I need the transformation string in the form "algorithm/mode/padding", I guessed that algorithm = RSA but I couldn't find out how to translate what the OpenSSL (above) documentation states about the padding into a valid cipher transformation string. I.e. what is mode for example?
Unfortunately this Android RSA decryption (fails) / server-side encryption (openssl_public_encrypt) accepted answer did not solve my problem.
Anyway might this solve my problem or does my problem originate elsewhere?
How would I further debug this? What is the correct way to transform the base64 decoded, decrypted key into a human readable form so I can compare it with the key used to encrypt?
I tried with:
String keyString = new String(keyBytes, "UTF-8");
But this doesn't give any human readable text back so I assume either the key is wrong or my method of transforming it.
Also decrypting the AES encrypted data in PHP the IV is needed in the decryption function mcrypt_decrypt. As you can see in the code I send it but it seems in Android this is not needed? Why so?
PS: I hope I provided all needed information, I can add further in the comments.
PPS: For completeness here is the Android client code making the HttpPost request:
#SuppressLint("TrulyRandom")
protected String doInBackground(URI... urls) {
try {
System.setProperty("jsse.enableSNIExtension", "false");
HttpClient httpClient = createHttpClient();
HttpPost httpPost = new HttpPost(urls[0]);
PRNGFixes.apply(); // fix TrulyRandom
KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
keygen.initialize(2048);
KeyPair keypair = keygen.generateKeyPair();
PublicKey publickey = keypair.getPublic();
byte[] publicKeyBytes = publickey.getEncoded();
String pubkeystr = "-----BEGIN PUBLIC KEY-----\n"+Base64.encodeToString(publicKeyBytes,
Base64.DEFAULT)+"-----END PUBLIC KEY-----";
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("publickey", pubkeystr));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
return new BasicResponseHandler().handleResponse(response);
} catch (Exception e) {
Toast toast = Toast.makeText(asyncResult.getContext(),
"unknown exception occured: " + e.getMessage(),
Toast.LENGTH_SHORT);
toast.show();
return "error";
}
}
You are generating one RSA keypair in doInBackground and telling the host to use the public half of that keypair to encrypt the DEK (data encryption key). You are then generating a completely different RSA keypair in getData and attempting to use the private half of that keypair to decrypt the encrypted DEK. The way public-key encryption works is you encrypt with the public half of a keypair and decrypt with the private half of the same keypair; the public and private halves are mathematically related. You need to save and use at least the private half of the keypair (optionally the keypair with both halves) whose public half you send.
Once you've got the DEK correctly, in order to decrypt CBC-mode data, yes you do need to use the same IV for decryption as was used for encryption. Your receiver needs to put it in an IvParameterSpec and pass that on the Cipher.init(direction,key[,params]) call. Alternatively if you can change the PHP, since you are using a new DEK for each message it is safe to use a fixed IV; easiest is to encrypt with '\0'x16 and allow the Java decrypt to default to all-zero.
Additionally you need to set Base64.decode with the parameter Base64.NO_WRAPas PHP will just put out the base64 delimited by \0. And to that you will also need to use the "AES/CBC/ZeroBytePadding" transformation cipher to decrypt the AES data as the PHP function mycrypt_encrypt will pad the data with zeros.
Here is what the getData function will have to look like:
public String getData() {
String dataDecrypted = null;
try {
byte[] cryptionKeyCrypted = Base64.decode(cryptionKeyCryptedBase64, Base64.NO_WRAP);
byte[] cryptionIV = Base64.decode(cryptionIVBase64, Base64.NO_WRAP);
Cipher cipherRSA = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
// get private key from the pair used to grab the public key to send to the api
cipherRSA.init(Cipher.DECRYPT_MODE, rsaKeyPair.getPrivateKey());
byte[] key = cipherRSA.doFinal(cryptionKeyCrypted);
byte[] dataCrytped = Base64.decode(dataCryptedBase64, Base64.NO_WRAP);
IvParameterSpec ivSpec = new IvParameterSpec(cryptionIV);
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipherAES = Cipher.getInstance("AES/CBC/ZeroBytePadding");
cipherAES.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
byte[] decryptedAESBytes = cipherAES.doFinal(dataCrytped);
dataDecrypted = new String(decryptedAESBytes, "UTF-8");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dataDecrypted;
}

Android AES Decrpyt string takes too long

I'm using AES Decryption on my Android Project to decrypt large string objects ( > 1 MB ).
I'm using this method :
public static String decryptAES(String cryptedString, byte[] byteArrayAESKey) {
try {
IvParameterSpec ips = new IvParameterSpec(General.InitVector.getBytes("UTF-8"));
SecretKey aesKey = new SecretKeySpec(byteArrayAESKey, "AES");
byte[] TBCrypt = Base64.decode(cryptedString, Base64.DEFAULT);
// Decryption cipher
Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
// Initialize PBE Cipher with key and parameters
decryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ips);
// Decrypt the cleartext
byte[] deciphertext = decryptCipher.doFinal(TBCrypt); // this may take a long time depending on string input length
return new String(deciphertext, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
Log.e("AES", "Decrypt failed : " + e.getMessage());
return "";
}
}
It works well, but on large encrypted strings, it takes a long time on many devices.
Is there a way to improve this method on android devices ? Should I cut the encrypted string to accelerate the process ? Should I use SpongyCastle ?
byte[] deciphertext = decryptCipher.doFinal(TBCrypt); Dont do that! Instead consider using streams, maybe directly to output file stream (if needed)?.
Is there a way to improve this method on android devices ?
Maybe, you could take a look here , and there's saying that the AES is pretty fast, though.
Should I cut the encrypted string to accelerate the process ?
Yes, this should be the problem. Usually you only have to encrypt the critical parts of the data. Maybe a refactor should resolve the question.
Should I use SpongyCastle ?
Don't know, but if i where you i would first look at the data encrypted.

Security in Android - Google app engine system

So i have an android app, and a google app engine server written in python.
The android app needs to send some sensible information to the server, and the way I do that is by doing an http post.
Now i have been thinking about encrypting the data in android before sending it, and decrypting it once it is on the gae server.
This is how i encrypt and decrypt in java :
private static final String ALGO = "AES";
public static String encrypt(String Data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes());
// String encryptedValue = new BASE64Encoder().encode(encVal);
byte[] decoded = Base64.encodeBase64(encVal);
return (new String(decoded, "UTF-8") + "\n");
}
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue =Base64.decodeBase64(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(Constant.keyValue, ALGO);
return key;
}
And this is how i try to decrypt on the server (i don't know yet how to do the encryption..maybe you guys can help with that too)
def decrypt(value):
key = b'1234567891234567'
cipher = AES.new(key, AES.MODE_ECB)
msg = cipher.decrypt(value)
return msg
As i looked in the logs, the string test that i get is : xVF79DzOplxBTMCwAx+hoeDJhyhifPZEoACQJcFhrXA= and because it is not a multiple of 16 (idk why, i guess this is because of the java encryption) i get the error
ValueError: Input strings must be a multiple of 16 in lenght
What am i doing wrong?
Why are you not using ssl (aka https)? That should provide all the encryption needed to transport data securely and privately between the phone and App Engine.
The basics of it: Instead of sending data to http://yourapp.appspot.com/, send it to https://yourapp.appspot.com/.
For a complete secure and authenticated channel between App Engine and Android, you can use Google Cloud Endpoints. It will even generate the Android side code to call it.
Java:
https://developers.google.com/appengine/docs/java/endpoints/
https://developers.google.com/appengine/docs/java/endpoints/consume_android
Python:
https://developers.google.com/appengine/docs/python/endpoints/
https://developers.google.com/appengine/docs/python/endpoints/consume_android
For a longer show and tell, check the IO 13 talk: https://www.youtube.com/watch?v=v5u_Owtbfew
This string "xVF79DzOplxBTMCwAx+hoeDJhyhifPZEoACQJcFhrXA=" is a base64-encoded value.
https://en.wikipedia.org/wiki/Base64
Base64 encoding is widely used lots of applications, it's a good way to encode binary data into text. If you're looking at a long encoded value, the "=" at the end can be a good indicator of base64 encoding.
In your python code you probably need to base64 decode the data before handing it to the decryption function.
I have two recommendations:
If crypto isn't a comfort zone for you, consult with someone who is good in this area for your project.
Be aware that embedding a symmetric encryption key in an Android app that you distribute is a bad idea. Anyone that can get a copy of your app can extract that key and use it to decrypt or spoof your messages.

CryptoJS AES and Java AES encrypted value mismatch

I am trying to encrypt in client and decrypt in sever using AES,
so using cryptojs to encrypt in client side with CBC mode and nopadding
in server side also using Cipher class with same mode and nopadding
function call()
{
var key = CryptoJS.enc.Hex.parse('roshanmathew1989');
var iv = CryptoJS.enc.Hex.parse('roshanmathew1989');
var encrypted = CryptoJS.AES.encrypt("roshanmathew1989",key,{ iv: iv},
{padding:CryptoJS.pad.NoPadding});
alert(encrypted.ciphertext.toString(CryptoJS.enc.Base64));
alert(encrypted.iv.toString());
}
Server side code
public class Crypto
{
private static byte[] key = null;
public void setKey(String key){this.key=key.getBytes();}
public String encrypt(String strToEncrypt)
{
String encryptedString =null;
try
{
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
final SecretKeySpec secretKey = new SecretKeySpec(key,"AES");
System.out.println("sdfsdf = "+key.toString());
IvParameterSpec ips = new IvParameterSpec(key);
cipher.init(Cipher.ENCRYPT_MODE, secretKey,ips);
encryptedString = Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes()));
}
catch(Exception e)
{
System.out.println(" ERROR : "+e.getMessage());
}
return encryptedString;
} other method omitted ....
implementation
Crypto cry=new Crypto();
cry.setKey("roshanmathew1989");
String s=cry.encrypt("roshanmathew1989");
Results
Browser side value = O64X/bKNBu7R2Tuq2lUbXeFlQ7wD2YnFasyyhsVUryw=
Server side value of s = RrNcVIER/75fzdjHr884sw==
Can anybody point out the mistake?
There are a few things wrong with the code:
you are using hexadecimal decoding of the key in JavaScript, and String.getBytes() - character encoding without specifying the character set - in Java
your key is 16 characters (it should be 16, 24 or 32 randomized bytes), but it is not in hexadecimals
you are encrypting instead of decrypting on the "server side", although that one is probably on purpose
Take another good look on how to perform encoding and character-encoding, they are essential for good crypto and often performed incorrectly (it's probably the most common issue on Stackoverflow regarding encryption)

Categories