I have a case where a 'secret' is coming to me from a Java App and it's cipher'd using a public key and the RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING cipher. I'm trying to decipher it at my end, but I'm not sure how to get the equivalent of that cipher. I've been using phpseclib for other security stuff, and I've tried the OAEP encryption mode in there, but to no avail. I just get a decrypt error with no information. I just want to state that the keys are correct:
function oaes_decrypt($ciphertext, $privatekey) {
$rsa = new \Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$rsa->setMGFHash('sha256');
$rsa->setHash('sha256');
$rsa->loadKey($privatekey);
return $rsa->decrypt($ciphertext);
}
Any help will be greatly appreciated! Thank you!
Try $rsa->setMGFHash('sha1'); The SHA-256 in RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING doesn't refer to the MGF1 hash. To have that be sha256 you'd have to be doing this:
Cipher oaepFromInit = Cipher.getInstance("RSA/ECB/OAEPPadding");
OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-1"), PSpecified.DEFAULT);
oaepFromInit.init(Cipher.DECRYPT_MODE, privkey, oaepParams);
byte[] pt = oaepFromInit.doFinal(ct);
System.out.println(new String(pt, StandardCharsets.UTF_8));
The final result, that works, in PHP:
function oaes_decrypt($ciphertext, $privatekey) {
$rsa = new \Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$rsa->setMGFHash('sha1');
$rsa->setHash('sha256');
$rsa->loadKey($privatekey);
return $rsa->decrypt($ciphertext);
}
Related
I am encrypting a file in Java and need to decrypt it at client side.
This is the server side code:
Key secretKey = new SecretKeySpec("mysecretmysecret".getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] outputBytes = cipher.doFinal(read(sampleFile));
return outputBytes;
At client side I use Ajax request to fetch the file and use CryptoJS AES:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
var encryptedData = this.response;
var decrypted = CryptoJS.AES.decrypt(encryptedData, "mysecretmysecret");
console.log(decrypted);
};
xhr.send();
But this does not decrypt the file. I get this printed as value of decrypted in the console:
W…y.init {words: Array[0], sigBytes: 0}
I have also tried converting arraybuffer to WordArray suggested here but still the same result.
I would be more than glad if someone could point me in the right direction and tell me what I did wrong.
Edit 1:
I have solved the issue. The code I used is posted as an answer.
So I have finally solved this. Thanks to Artjom for pointing in the right direction.
I have changed my Java code to use CBC with PKCS5Padding .
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec myKey = new SecretKeySpec("mysecretmysecret".getBytes(), "AES");
IvParameterSpec IVKey = new IvParameterSpec("mysecretmysecret".getBytes());
cipher.init(Cipher.ENCRYPT_MODE, myKey, IVKey);
byte[] outputBytes = cipher.doFinal(read(sampleFile));
return outputBytes;
And my javascript goes like this:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
var encryptedData = this.response;
var passwordWords = CryptoJS.enc.Utf8.parse("mysecretmysecret"); //yes I know, not a big secret!
var wordArray = CryptoJS.lib.WordArray.create(encryptedData);
var decrypted = CryptoJS.AES.decrypt({
ciphertext: wordArray
}, passwordWords, {
iv: passwordWords, //yes I used password as iv too. Dont mind.
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
console.log(decrypted); //Eureka!!
};
xhr.send();
The decrypted is a WordArray.
Let's recap, in Java you're using
AES,
ECB (not specified but most often the default; it's insecure!),
PKCS#7 padding (not specified but most often the default; it's the same as PKCS#5 padding), and
a password of 16 characters as a key of 16 bytes (depending on the default system encoding).
If the key is passed as a string to CryptoJS, it will have to derive the key from the assumed password using OpenSSL's EVP_BytesToKey with a single round of MD5. Since your ciphertext is not encoded in an OpenSSL-compatible format, it will fail. The thing is, you don't need that.
The following code would decrypt the ciphertext that is coming from Java correctly, but it's not very secure:
var passwordWords = CryptoJS.enc.Utf8.parse("mysecretmysecret");
var decrypted = CryptoJS.AES.decrypt({
ciphertext: CryptoJS.lib.WordArray.create(encryptedData) // or use some encoding
}, passwordWords, {
mode: CryptoJS.mode.ECB
});
console.log(decrypted.toString(CryptoJS.enc.Utf8)); // in case the plaintext is text
The ECB mode is not included in the basic rollup, so you will have to include that JavaScript file in your page after the main CryptoJS file.
Also, CryptoJS doesn't handle an ArrayBuffer by default. You need to include the shim for that (source: this answer).
The problem with this is its insecurity. ECB mode is very insecure.
Never use ECB mode. It's deterministic and therefore not semantically secure. You should at the very least use a randomized mode like CBC or CTR. The IV/nonce is not secret, so you can send it along with the ciphertext. A common way is to put it in front of the ciphertext.
It is better to authenticate your ciphertexts so that attacks like a padding oracle attack are not possible. This can be done with authenticated modes like GCM or EAX, or with an encrypt-then-MAC scheme.
Keys can be derived from passwords, but a proper scheme such as PBKDF2 should be used. Java and CryptoJS both support these.
I got on this post a couple of weeks ago and worked perfectly:
Compatible AES algorithm for Java and Javascript
Now, I need to do the reverse operation, but once in java, I am getting this exception:
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:966)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
This is my "reverse" operation I did in JavaScript:
var rkEncryptionKey = CryptoJS.enc.Base64.parse('u/Gu5posvwDsXUnV5Zaq4g==');
var rkEncryptionIv = CryptoJS.enc.Base64.parse('5D9r9ZVzEYYgha93/aUK2w==');
function encryptString(stringToEncrypt) {
var utf8Stringified = CryptoJS.enc.Utf8.parse(stringToEncrypt);
var encrypted = CryptoJS.AES.encrypt(utf8Stringified.toString(), rkEncryptionKey, {mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv: rkEncryptionIv});
return CryptoJS.enc.Base64.parse(encrypted.toString()).toString();
}
I though this would be all?
[EDIT]
Encrypted string is the following: {"company_name":"asdfasdfasd","customer_name":"asdfasdfasdfasdf","phone_number":"asdfasdfasdfasdf","email":"asdfasdfasdfasdfads"}
When doing the encrypt / decrypt from java to java it works, when doing so from java to javascript, also works, but from javascript to java, not working.
Java Code
public String toJson(final String encrypted) {
try {
SecretKey key = new SecretKeySpec(Base64.decodeBase64("u/Gu5posvwDsXUnV5Zaq4g=="), "AES");
AlgorithmParameterSpec iv = new IvParameterSpec(Base64.decodeBase64("5D9r9ZVzEYYgha93/aUK2w=="));
byte[] decodeBase64 = Base64.decodeBase64(encrypted);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return new String(cipher.doFinal(decodeBase64), "UTF-8");
} catch (Exception e) {
throw new RuntimeException("This should not happen in production.", e);
}
}
Change
return CryptoJS.enc.Base64.parse(encrypted.toString()).toString();
to
return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
The encrypted object usually stringifies into an OpenSSL format which might also contain the salt. If you're only interested in the actual ciphertext, then you need to stringify the ciphertext property.
Note that toString() takes an optional encoding function. Use the one that you need.
I try to decrypt an encrypted data that I receive from a web service.
The encryption is done using AES 128.
I use the following code to decrypt the data:
public static String decrypt(String strToDecrypt)
{
try
{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); //AES/CBC/PKCS7Padding
SecretKeySpec secretKey = new SecretKeySpec(AppConstants.AESEncryptionKey.getBytes("UTF8"), "AES");
int blockSize = cipher.getBlockSize();
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(new byte[blockSize])); //new IvParameterSpec(new byte[16])
byte decBytes[] = cipher.doFinal(Base64.decode(strToDecrypt, 0));
// byte decBytes[] = cipher.doFinal(Base64.decodeBase64(strToDecrypt));
String decStr = new String(decBytes);
System.out.println("After decryption :" + decStr);
return decStr;
}
catch (Exception e)
{
System.out.println("Exception in decryption : " + e.getMessage());
}
return null;
}
At
cipher.doFinal()
I got the following Exception:
javax.crypto.badpaddingexception pad block corrupted
I went through my post but ended up with no solution. I am badly stuck over here.
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG","Crypto");
works perfectly
Note: This code works only on devices up to Android 6. Starting with Android 7.0 the "Crypto" provider has been removed, therefore this code will fail.
AES keys should consist of random data. If you store them as a String then you are likely to loose information, especially if you use encodings such as UTF-8. Your line:
AppConstants.AESEncryptionKey.getBytes("UTF8")
Makes it likely that you've lost data during conversion to/from a string. Use hexadecimals instead if you require a string, or simply store the key as a byte array.
Note that this answer doesn't indicate any security related hints. In general you only want to derive keys or store them in containers. You don't want to use CBC over an insecure channel either.
In my case issue is came because encrypted key and decrypted key both are different, when I check both key with same value then issue is not came
I was asked to encrypt some text from client side ( web ) before sending it to server side ( java )
So i try to use CryptoJS library for client side.
I encrypt it like this :
var key = "aaaaaaaaaaaaaaaaaaaaaaaa";
var value = "KF169841";
var encryptedString = CryptoJS.TripleDES.encrypt(value, key);
console.log(encryptedString.toString());
And i get something like this : U2FsdGVkX19eYFFHgYGCr3v9/skTOKVp0pLWRNK9JTg=
I use this encryptedString and key in other Decrypt tool online ( Which also use CryptoJS ) and got back exact value KF169841.
After sending this value and key to server ( well key isn't sending directly to server though but for test, it is ), i need to decrypt it using Java.
But i quite don't know how to decrypt it. I'm tried some code from google search but it end up wrong padding if use DESese or get wrong value if i use ECB/NoPadding.
I did try to something like setting sfg for CryptoJS side like:
mode: CryptoJS.mode.EBC,
padding: CryptoJS.pad.NoPadding
But they got javascript exception ( a is not define )
So any have any experience with CryptoJS can help me decrypt this one using java ?
=============================================================
UPDATE : Sorry here my server side code i'm using
/**
* Method To Decrypt An Ecrypted String
*/
public String decrypt(String encryptedString, String myEncryptionKey) {
String decryptedText = null;
try {
byte[] keyAsBytes = myEncryptionKey.getBytes("UTF8");
KeySpec myKeySpec = new DESedeKeySpec(keyAsBytes);
SecretKeyFactory mySecretKeyFactory =
SecretKeyFactory.getInstance("DESede");
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
SecretKey key = mySecretKeyFactory.generateSecret(myKeySpec);
cipher.init(Cipher.DECRYPT_MODE, key);
// BASE64Decoder base64decoder = new BASE64Decoder();
// byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
byte[] encryptedText = org.apache.commons.codec.binary.Base64.decodeBase64(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText= bytes2String(plainText);
} catch (Exception e) {
e.printStackTrace();
}
return decryptedText;
}
According to the documentation, your encryptedString variable contains structured data that must be split apart to be sent to Java code. You will need to send encryptedString.iv and encryptedString.ciphertext to your Java code. If you continue to use passwords (see below), you will need to send encryptedString.salt as well.
If you pass your key as a string it will be interpreted as a password and a key will be derived from it. If you actually want to pass an explicit key, follow the documentation and specify the IV and key as suggested by the code snippet below. If you stick with supplying a password, then you must figure out the derivation scheme and use the same process in your Java code.
// Code snippet from http://code.google.com/p/crypto-js/#Custom_Key_and_IV
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script>
var key = CryptoJS.enc.Hex.parse('000102030405060708090a0b0c0d0e0f');
var iv = CryptoJS.enc.Hex.parse('101112131415161718191a1b1c1d1e1f');
var encrypted = CryptoJS.AES.encrypt("Message", key, { iv: iv });
</script>
Regarding your Java code, it looks mostly OK (although there is plenty of room for error with string conversions). However, you probably want to convert your key from hex to binary rather than grabbing the bytes:
byte[] keyAsBytes = DatatypeConverter.parseHexBinary(myEncryptionKey);
This assumes you alter your JavaScript code to pass the literal key value.
You will also need to switch to DESede/CBC/PKCS5Padding and pass an IVParameterSpec object to your Cipher.init call, specifying the IV value sent from your Java Script code.
I'm trying to encrypt stuff in java using the public key generated by my PHP:
PHP Code
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
$keys = $rsa->createKey(1024);
extract($keys);
echo (base64_encode($publickey));
For testing purposes, I've set aside a keypair (base64) of the above format.
I retrieve my Public Key in java and base64 decode it.
String publicKeyDecoded = new String(Base64.decode(publicKey));
PEMParser pr = new PEMParser(new StringReader(publicKeyDecoded));
Object obj = pr.readObject();
pr.close();
SubjectPublicKeyInfo spki = (SubjectPublicKeyInfo) obj;
AsymmetricKeyParameter askp = PublicKeyFactory.createKey(spki);
AsymmetricBlockCipher e = new RSAEngine();
e = new org.bouncycastle.crypto.encodings.PKCS1Encoding(e);
e.init(true, askp);
byte[] messageBytes = plainText.getBytes();
byte[] encryptedData = e.processBlock(messageBytes, 0, messageBytes.length);
byte[] encryptedDataBase = Base64.encode(encryptedData);
I send the Base64 encrypted plaintext back to PHP for decryption using the following:
$rsa->loadKey($privatekey) or die ("Cant load");
echo $rsa->decrypt($cipher);
It's unable to decrpyt my encoded message and throws me the error:
Decryption error in <b>/opt/lampp/htdocs/Crypt/RSA.php</b> on line <b>2120</b>
Can someone point me to the right direction? It's been hours since I'm trying to figure this out.
I'm using a hardcoded keypair so I guess there's no question of my keys being wrong...
To answer my own question:
Everything apart from the final decryption PHP was correct.
It should be:
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
$rsa->loadKey(base64_decode($_SESSION['private'])) or die ("Cant load");
echo $rsa->decrypt(base64_decode($cipher));
I forgot to un-base64 my encrypted text sent from java and to set the encryption modes.
Thanks neubert.