I'm trying to encrypt an audio file in Android. This file is then getting decrypted on the server-side by a PHP script. While encrypting the file I'm getting an Java.security.InvalidKeyException: Key length not 128/192/256 bits
My code is as follows:
if(getFileToEncrypt.exists()){
System.out.println("-----------FILE EXISTS--------------");
secRand = SecureRandom.getInstance("SHA1PRNG");
key = new BigInteger(128, secRand).toString(16);
rawKey = key.getBytes();
sKeySpec = new SecretKeySpec(rawKey, "AES");
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
inputStream = new FileInputStream(getFileToEncrypt);
byte[] byts = new byte[(int) getFileToEncrypt.length()];
inputStream.read(byts);
inputStream.close();
encrypted = cipher.doFinal(byts);
encryptedFile.createNewFile();
ostr = new FileOutputStream(encryptedFile);
ostr.write(encrypted);
ostr.close();
System.out.println("--------FILE ENCRYPTION COMPLETE----------");
}
This works at times but otherwise ends up with an Exception.
The stack trace is as follows:
07-08 15:38:02.865: W/System.err(16391): java.security.InvalidKeyException: Key length not 128/192/256 bits.
07-08 15:38:02.865: W/System.err(16391): at com.android.org.bouncycastle.jce.provider.JCEBlockCipher.engineInit(JCEBlockCipher.java:570)
key = new BigInteger(128, secRand).toString(16);
rawKey = key.getBytes();
That doesn't do what you think it does.
This code creates a hexadecimal string representing a number with at most 128 bits, then gets the bytes that encode that string in the platform default encoding.
This is (a) very low-entropy (each byte can only have one of 16 values) and (b) far longer than what you want (1 byte for every 4 bits of original data).
You should not be using numbers here at all; instead, you should generate random bytes directly, by calling the nextBytes() method.
Related
In android i get always IllegalBlockSizeException, the data are encrypted in nodejs server and looks like (node.js: encrypting data that needs to be decrypted?):
var crypto = require('crypto');
console.log(crypto.getCiphers(), crypto.getHashes());
var algorithm = 'aes128'; // or any other algorithm supported by OpenSSL
var key = 'password';
var cipher = crypto.createCipher(algorithm, key);
var encrypted = cipher.update(data, 'utf8', 'binary') + cipher.final('binary');
fs.writeFile(file, encrypted, function (err) {
cb(err);
});
android code:
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
call method from file is in input stream (is):
byte [] b = new byte[2000000];
is.read(b, 0, 2000000);
byte[] decryptedData = decrypt(key,"password".getBytes());
result = new String(decryptedData, "UTF8").split("\n");
android code is inspired by : android encryption/decryption with AES where i dont use part of SecretKey with SecureRandom... which is for sure wrong, but i dont use any secure random in node.js part. The problem can be also with coding data in file.
I generaly generate a file in nodejs which is downloaded by app and stored in sdcard i'm not sure if i should be realy care about these data but will be cool have it crypted, isn't it?:-)
Thank you so much for any help or advice;-)
An IllegalBlockSizeException means that your input is not a multiple of the AES block size (16 bytes).
Your use of the decryption method looks completely wrong:
byte [] b = new byte[2000000];
is.read(b, 0, 2000000);
byte[] decryptedData = decrypt(key,"password".getBytes()); // <--- ???!
You are passing an eight byte constant value for your ciphertext. Instead, you should be passing the data you read from your input stream.
I would strongly recommend you research the correct way to read an entire input stream, because this code snippet suggests you are not handling resources correctly. You are also likely to end up with a byte array much larger than your actual data (unless your file is exactly 2000000 bytes long).
Side note: always specify the mode and padding when creating a Cipher object. For instance, if you know your JavaScript code uses CBC-mode and PKCS#7 padding, select:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
This is important, because otherwise you are relying on default values that may differ between platforms.
I'm figuring out how to do cross platform (Android & Python) encryption&decryption using AES, and I seem to succeed transferring data if I use a String based IV. But immediately if I switch to using bytes generated with SecureRandom.generateSeed(), it goes awry.
The secret keys are preshared.
Working Android code (try/catch blocks removed to keep it short):
String SecretKey = "0123456789abcdef";
String iv = "fedcba9876543210";
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
SecretKeySpec keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//Initialize the cipher
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
String message = "What's up?";
byte[] encrypted = cipher.doFinal(message.getBytes());
//Send the data
outputStream.write(encrypted);
There is a small transfer header that let's the client know the size of the incoming message, but I thought it's not relevant and I left that out.
The Python code receiving this message looks like:
#Predefined:
unpad = lambda s : s[0:-ord(s[-1])]
encrypted = cs.recv(messagesize) # Receive the encrypted message
iv = encrypted[:16]
key = AES.new('0123456789abcdef', AES.MODE_CBC,IV=iv)
padded_msg = key.decrypt(encrypted[16:])
decrypted = unpad(padded_msg) #Remove padding
print "read [%s]" % decrypted
Result looks like:
read [What's up]
And if I change two lines in Java code:
SecureRandom rnd = new SecureRandom();
IvParameterSpec ivspec = new IvParameterSpec(rnd.generateSeed(16));
Python output becomes:
read [?=H��m��lڈ�1ls]
I wonder what changes with the SecureRandom? I read that by default the String.getBytes() return platform default encoding (for Android 4.0), so I wonder if I have to do some manipulation on Python end to the IV that was generated with SecureRandom..?
The recipient needs to be told what the IV is. Look at the section on CBC in this Wikipedia entry: you can see that an encrypted n-block message consists of n+1 blocks, the additional block being the IV. There is no standard protocol for transmitting it, but every code i've seen does this by prepending the IV to the message, which really is the natural thing to do and thanks to the error-correcting properties of CBC works even when the code gets it slightly wrong. For example, you can find code in the wild that uses a constant IV but prepends the plain text with a random block, which basically does the same thing in a different way. Sometimes you'll find that kind of code even in books, like the InlineIvCBCExample.java in chapter 2 of David Hook's otherwise very good book.
I recommed the following way of doing AES/CBC/PKCS7Padding:
byte[] plaintext = ...;
byte[] key = ...;
// get iv
SecureRandom rnd = new SecureRandom();
byte[] iv = rnd.getBytes(16);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
// encrypt
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] ciphertext = cipher.doFinal(plaintext);
// copy to result
byte[] result = new byte[iv.length + ciphertext.length];
System.arraycopy(iv, 0, result, 0, iv.length);
System.arraycopy(ciphertext, 0 , result, iv.length, ciphertext.length);
In my project i am working on AES encryption and Decryption.i have used this algorithm to encrypt and decryption a string and storing the string in the sq-lite database.Now i get that encrypted key from database and try to decryption it but it shows an Exception (pad Block corrupted).I am converting the Encrypted string into the bytes by using
public static byte[] hexStringToByteArray(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 getting the correct Bytes but while converted into the String it shows 'pad block corrupted'.
Thanks in advance.really appreciate if find answer.
my code is
dh=new data_helper(Resy.this);
mac_db=dh.getData();
// getdata=mac_db.toString();
KeyGenerator kgen;
try {
kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
getdata=mac_db.toString();
// byte g1[]=getdata.getBytes();
// System.out.println(g1);
byte b[]=hexStringToByteArray(getdata);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] m1=cipher.doFinal(b); // here pad block corrupt exception came.
String originalString_mac = new String(original_macadress);
Toast.makeText(getApplicationContext(),"Original : " +originalString_mac + " " + asHex(original_macadress) , Toast.LENGTH_LONG).show();
First make sure your data is the correct length and there are not errors in your hex conversion. Next you need to use the same key for encryption and decryption. From the code above it looks like you are generating a new key every time. This will not work: even if the decryption succeeds you will get something very different from the original plain text. Then Cipher cipher = Cipher.getInstance("AES"); might produce a cipher using a random IV, which you will need to decrypt. It is better to specify an explicit transformation string like so:
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
In short, find a working sample and start there. Something like this.
you have to do Base64 encoding of it to get proper AES encrypt/decrypt to work.
Do it as follows.
For encrytion : Original String --> Aes encryption > base64 encode --->(encrypted string)
For decryption : encrypted string ---> base64 decode > aes decryption ---> Original String
I am trying to implement AES128 algorithm on Android, and I have referenced this link for a basic AES implementation (http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html).
The problem is,for my project the key is predefined, and it is 36 bytes, not 16/24/32 bytes. So I always got a "key length not 128/194/256 bits" exception. I try the solution from iphone sdk(see this link: The iOS encryption framework) and it works even when I pass a 36 byte predefined key. As I can not find the implementation details for the BlockCipher.c/CommonCryptor.c released by Apple, Can any body help me figure out how they select 16 bytes from 36 bytes?
Thanks.
-----------------------------------update Sep 13th------------------------------------
In order to avoid confusion I provide some sample and my progress. I change some data that is confidential, but the length and format remain the same. And for saving time I only reveal the core functions. No comments for the code as I think the code is self-explained enough.
the iOS sample:
NSString * _key = #"some 36 byte key";
StringEncryption *crypto = [[[StringEncryption alloc] init] autorelease];
NSData *_inputData = [inputString dataUsingEncoding:NSUTF8StringEncoding];
CCOptions padding = kCCOptionPKCS7Padding;
NSData *encryptedData = [crypto encrypt:_inputData key:[_key dataUsingEncoding:NSUTF8StringEncoding] padding:&padding];
NSString *encryptedString = [encryptedData base64EncodingWithLineLength:0];
return encryptedString;
the [crypto encrypt] implementation is exactly the same as the link I mentioned above. It calls the doCipher in encryption mode. The core functions includes CCCryptorCreate, CCCryptorUpdate and CCCryptorFinal, which are from . The CCCryptorCreate deals with the key length. It passes the raw key bytes, and pass an integer 16 (kCCKeySizeAES128) as the key size and do the trick. The call hierarchy is like CCCryptorCreate/CommonCryptor.c => ccBlockCipherCallouts->CCBlockCipherInit/BlockCipher.c => ccAlgInfo->setkey/BlockCipher.c . setkey is actually a pointer to a function, for AES it points to aes_cc_set_key. And I can not find the aes_cc_set_key implementation, got lost here.
----------------------------------------Update Sep 13th -----------------------------
I change the _key in iOS sample code, manually taking the first 16 byte as the new key, other parts remain the same, and it is working!!! Up to this point I solve the key length problem.
But the Android version outputs different from the iOS version for some long plain text, like 30 or 40 bytes. my java implementation is like below:
String key = "some 16 byte key";
byte[] keyBytes = key.getBytes("UTF-8");
byte[] plainBytes = plainText.getBytes("UTF-8");
SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(plainBytes);
String result = Base64.encodeBytes(encrypted);
return result;
Base64 is from org.apache.commons.codec.binary.Base64. What is the problem? or any hints on c/c++ libraries that can do the same thing? I can import it into android as well.
The remaining difference (provided that you only used the first 16 bytes of the key) is the cipher streaming mode. The iOS code uses CBC mode with an initialization set to all zeros. The Android code however uses ECB.
So the correct Java/Android code is:
// convert key to bytes
byte[] keyBytes = key.getBytes("UTF-8");
// Use the first 16 bytes (or even less if key is shorter)
byte[] keyBytes16 = new byte[16];
System.arraycopy(keyBytes, 0, keyBytes16, 0, Math.min(keyBytes.length, 16));
// convert plain text to bytes
byte[] plainBytes = plainText.getBytes("UTF-8");
// setup cipher
SecretKeySpec skeySpec = new SecretKeySpec(keyBytes16, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[16]; // initialization vector with all 0
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv));
// encrypt
byte[] encrypted = cipher.doFinal(plainBytes);
I have tested it with about 100 bytes of data and got exactly the same result on iOS and in Java.
There is no such thing as a 36-byte (288 bits) AES key. AES 256 would use a 32 byte key, so maybe that is what you have, with some additional header/trailer bytes. Where did you get this key from? What is the format? The Apple implementation may be throwing away the unneeded bytes, or it already knows about that special format you are using.
Is the 36 bytes actually a passphrase? If so, then it is likely that the key being used is SHA-256(passphrase) or SHA-512(passphrase).
ETA:
Re your update. I note that your code is using ECB mode. That is insecure. It may well be that Apple is using CBC mode, hence you difficulty in decrypting longer (more than 16 bytes) messages. Try changing the mode to CBC and using 16 more bytes of your mysterious input as the IV. Looking quickly at the Apple code for CommonCryptor.c, they appear to be using PKCS7 padding, so you should use that as well.
In case you want to apply base64 encoding for transporting over the network this is the right code:
public String encryptString(String string, String key)
{
byte[] aesData;
String base64="";
try
{
aesData = encrypt(key, string.getBytes("UTF8"));
base64 = Base64.encodeToString(aesData, Base64.DEFAULT);
}
catch (Exception e)
{
e.printStackTrace();
}
return base64;
}
public String decryptString(String string, String key)
{
byte[] debase64 = null;
String result="";
try
{
debase64=Base64.decode(string, Base64.DEFAULT);
byte[] aesDecrypted = decrypt(key, debase64);;
result = new String(aesDecrypted, "UTF8");
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
private byte[] decrypt(String k, byte[] plainBytes) throws Exception
{
// convert key to bytes
byte[] keyBytes = k.getBytes("UTF-8");
// Use the first 16 bytes (or even less if key is shorter)
byte[] keyBytes16 = new byte[16];
System.arraycopy(keyBytes, 0, keyBytes16, 0, Math.min(keyBytes.length, 16));
// setup cipher
SecretKeySpec skeySpec = new SecretKeySpec(keyBytes16, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[16]; // initialization vector with all 0
cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(iv));
// encrypt
byte[] encrypted = cipher.doFinal(plainBytes);
return encrypted;
}
private byte[] encrypt(String k, byte[] plainBytes) throws Exception
{
// convert key to bytes
byte[] keyBytes = k.getBytes("UTF-8");
// Use the first 16 bytes (or even less if key is shorter)
byte[] keyBytes16 = new byte[16];
System.arraycopy(keyBytes, 0, keyBytes16, 0, Math.min(keyBytes.length, 16));
// setup cipher
SecretKeySpec skeySpec = new SecretKeySpec(keyBytes16, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[16]; // initialization vector with all 0
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv));
// encrypt
byte[] encrypted = cipher.doFinal(plainBytes);
return encrypted;
}
The situation:
I want an application that encrypts an string using RSA. I have the public key stored in res/raw, and as the key is 1024 bits, the resulting string has to be 128 bytes long. However, the resulting string after encrypting is 124 long, and as a result, the decryption crashes.
The function I am using to recover the public key is:
private PublicKey getPublicKey() throws Exception {
InputStream is = getResources().openRawResource(R.raw.publickey);
DataInputStream dis = new DataInputStream(is);
byte [] keyBytes = new byte [(int) is.available()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
And the code of the function that I am using to encrypt:
private String rsaEncrypt (String plain) {
byte [] encryptedBytes;
Cipher cipher = Cipher.getInstance("RSA");
PublicKey publicKey = getPublicKey();
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plain.getBytes());
String encrypted = new String(encryptedBytes);
return encrypted;
}
P.D.: The code works perfectly in a desktop application, it just crashes in Android.
I really would appreciate any help,
Thank you very much.
String encrypted = new String(encryptedBytes);
is a bug. The output from crypto transforms are binary bytes. You cannot reliably store them as Strings.
Using is.available() is probably also a bug, but I'm not sure in this case.
Finally, it is one of my pet peeves when folks use the default charset versions of new String(...) and String.getBytes(). It is very rarely the right thing to do, especially in that Java claims to be "write once, run everywhere". The default charset is different on different platforms, which will trigger a bug in your code even if you do everything else correct. You should always specify a particular charset. In every case I have ever seen, simply using the UTF-8 Charset (Charset.forName("UTF-8");) will always work and represent data efficiently.