Best approach to generate a dynamic key in security [duplicate] - java

This question already has answers here:
How to create a secure random AES key in Java?
(3 answers)
Closed 8 years ago.
A defined key is used in this example:
byte[] keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 };
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
I need to know what is the recommended approach to generate dynamic enhanced unpredictable key, especially when security working with JAX-WS , JAX-RS web services.

That's what the SecureRandom class in Java is for:
SecureRandom random = new SecureRandom();
byte[] key = new byte[24]; // 24 or whatever your key length is
random.nextBytes(key);
SecureRandom provides a "a cryptographically strong random number generator (RNG)" according to the Javadoc documentation.
It's often faulted for being slow, but not for being insecure.

Related

How to have a constant initialization vector and secret key in java?

I'm trying to decrypt an access token (it's a String), which is used to default access an Dropbox account and uploading files into it. So right now, I always need that access token to make file uploadings.
Until now, I've been generating a new initialization vector (IV) and a new secret key to encrypt and decrypt the access token. However, I want to store these two in the source code, as constant variables/attributes. The reason why I want them to remain the same ? Because I will give a crypted access token (always the same encoded one) to the users, and the app should keep the IV and the secret key inside the source code.
How can I store them in my source code ?
I tried to write the string values of the IV and of the secret key in files. I use the string from the files, and I assign the string values to string constants in my code. Then i use my constants to create byte arrays for converting into the IV and into the secret key. I'm not sure if this will work yet, it's still in development.
You'd better heed the advice. Storing the key is bad but can sometimes be defended if no other options are available. There is however generally no reason to use a static IV. You can just prefix the IV (which is 16 bytes for most modes of operation) to the ciphertext instead.
Anyway, to store them as static values, just take a look at the following code; note that you should generate them as random values in advance, not the static values you're seeing here:
private static final byte[] KEY_DATA = {
(byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03,
(byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07,
(byte) 0x08, (byte) 0x09, (byte) 0x0A, (byte) 0x0B,
(byte) 0x0C, (byte) 0x0D, (byte) 0x0E, (byte) 0x0F,
};
private static final byte[] IV_DATA = {
(byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03,
(byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07,
(byte) 0x08, (byte) 0x09, (byte) 0x0A, (byte) 0x0B,
(byte) 0x0C, (byte) 0x0D, (byte) 0x0E, (byte) 0x0F,
};
public static void main(String[] args) throws Exception {
Cipher aes = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKey key = new SecretKeySpec(KEY_DATA, "aes");
IvParameterSpec iv = new IvParameterSpec(IV_DATA);
aes.init(Cipher.ENCRYPT_MODE, key, iv);
...
}
Note that SecretKeySpec implements the interface SecretKey for easy usage.

javax.crypto.Cipher working differently since Android 6 Marshmallow

I've been successfully using javax.crypto.Cipher.getInstance("DESede/CBC/NoPadding") to Authenticate with DESFire cards on Android (following the example here: https://stackoverflow.com/a/14160507/2095694). It's been working on several devices from Android 4 to 5, but stopped working on my Nexus 7 updated to 6 Marshmallow (and 6.0.1). It had been working on the same device before updating.
It seems Cipher is working differently, giving different results for the same key and data. Running the following code...
public static void testCipher() throws Exception
{
byte[] KEY =
new byte[]{
(byte) 0x0C, (byte) 0x09, (byte) 0x03, (byte) 0x0E,
(byte) 0x05, (byte) 0x0A, (byte) 0x0D, (byte) 0x02,
(byte) 0x03, (byte) 0x0A, (byte) 0x09, (byte) 0x0B,
(byte) 0x06, (byte) 0x10, (byte) 0x04, (byte) 0x10
};
byte[] DATA =
new byte[]{
(byte) 0x29, (byte) 0xDA, (byte) 0xC0, (byte) 0xC4,
(byte) 0xB8, (byte) 0x47, (byte) 0x13, (byte) 0xA2};
byte[] newByte8 = new byte[8]; //Zeroes
android.util.Log.d("TEST", "KEY : " + bin2hex(KEY));
android.util.Log.d("TEST", "DATA: " + bin2hex(DATA));
android.util.Log.d("TEST", "IVPS: " + bin2hex(newByte8));
android.util.Log.d("TEST", "----");
javax.crypto.Cipher cipher =
javax.crypto.Cipher.getInstance("DESede/CBC/NoPadding");
cipher.init(
Cipher.DECRYPT_MODE,
new javax.crypto.spec.SecretKeySpec(KEY, "DESede"),
new javax.crypto.spec.IvParameterSpec(newByte8));
byte[] result = cipher.doFinal(DATA);
android.util.Log.d("TEST", "RSLT: " + bin2hex(result));
}
public static String bin2hex(byte[] data) {
return String.format("%0" + (data.length * 2) + "X", new java.math.BigInteger(1, data));
}
... gives me the following output:
KEY : 0C09030E050A0D02030A090B06100410
DATA: 29DAC0C4B84713A2
IVPS: 0000000000000000
----
RSLT: 47BC415065B8155E
Normal value, what it should be, always worked and card ends up authenticating correctly, so it's doing it the way the card expects. As a said I tried on several devices (Android 4 and 5) and they give the same result.
But on my Nexus 7 now with Marshmallow I get something else (and the authentication ends up failing)
RSLT: F3ADA5969FA9369C
Has something changed in the libraries?
It seems they changed the default provider in Marshmallow.
A simple:
cipher.getProvider().getName();
Shows "AndroidOpenSSL" for Marshmallow, where it was "BC" (BouncyCastle I suppose) before.
Using the other getInstance overload...
javax.crypto.Cipher cipher =
javax.crypto.Cipher.getInstance("DESede/CBC/NoPadding","BC");
...gives me the expected result on my Nexus with Marshmallow.
Update: I now get this warning:
The BC provider is deprecated and when targetSdkVersion is moved to P this method will throw a NoSuchAlgorithmException. To fix this you should stop specifying a provider and use the default implementation
Cipher#getInstance should not be called with ECB as the cipher mode or without setting the cipher mode because the default mode on android is ECB, which is insecure.
So I have ended up using the other answer here that will (hopefully) work on all versions of Android.
there is a android bug issued:
https://code.google.com/p/android/issues/detail?can=2&start=0&num=100&q=triple%20des&colspec=ID%20Status%20Priority%20Owner%20Summary%20Stars%20Reporter%20Opened&groupby=&sort=&id=189292
you can also solve your problem by changing you key to 24 bytes len as below:
MessageDigest md = MessageDigest.getInstance("MD5");
seed_key = md.digest(new String(key).getBytes());
if (seed_key.length == 16) {
byte[] tempkey = new byte[24];
System.arraycopy(seed_key, 0, tempkey, 0, 16);
System.arraycopy(seed_key, 0, tempkey, 16, 8);
seed_key = tempkey;
}
SecretKeySpec keySpec = new SecretKeySpec(seed_key, "DESede");
nCipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
byte[] IVector = new byte[] { 27, 9, 45, 27, 0, 72, (byte) 171, 54 };
IvParameterSpec iv = new IvParameterSpec(IVector);
nCipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] cipherbyte = nCipher.doFinal(data.getBytes());
encodeTxt = new String(Base64.encodeBase64(cipherbyte));

How to avoid individual casting to byte during initialization of byte array in Java

I am using a byte array to store a text file outside of the filesystem.
It looks like this:
private static final byte[] CDRIVES = new byte[] {
(byte)0xe0, 0x4f, (byte)0xd0, 0x20, (byte)0xea, 0x3a, 0x69, 0x10,
(byte)0xa2, (byte)0xd8, 0x08, 0x00, 0x2b, 0x30, 0x30, (byte)0x9d,
(byte)0xba, (byte)0x8a, 0x0d, 0x45, 0x25, (byte)0xad, (byte)0xd0, 0x11,
(byte)0x98, (byte)0xa8, 0x08, 0x00, 0x36, 0x1b, 0x11, 0x03,
(byte)0x80, 0x53, 0x1c, (byte)0x87, (byte)0xa0, 0x42, 0x69, 0x10,
(byte)0xa2, (byte)0xea, 0x08, 0x00, 0x2b, 0x30, 0x30, (byte)0x9d
...
...
...
};
Is there a way to avoid casting to (byte) for better visual interpretation?
I don't mind using other data type, but I need to be able build an InputStream out of it and do it the fastest way if possible. (for example storing a text file into a String variable is not the best way...)
Well one simple approach would be to use base64 - but perform the conversion on class initialization, so you only take the performance hit once:
private static final byte[] CDRIVES = Base64.decode("YOURBASE64HERE");
Or if it's genuinely text, perform that encoding once in a similar way:
private static final byte[] CDRIVES =
"Your constant text here".getBytes(StandardCharsets.UTF_8);
Again, the performance hit occurs exactly once, and then you can use the bytes multiple times. I would be very surprised if the cost of encoding text into bytes at class initialization time is genuinely a bottleneck for you.

Java:AES Encryption using CTR mode; unable to decrypte

I am using following code but It's not decrypting the text properly, what am I getting as output is
ciphered: %öNo2F?¢¶SHºûÅ“?¾
plaintext: hello × am originÎl
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
// Dernier exemple CTR mode
// Clé 16 bits
byte[] keyBytes = new byte[] { (byte) 0x36, (byte) 0xf1, (byte) 0x83,
(byte) 0x57, (byte) 0xbe, (byte) 0x4d, (byte) 0xbd,
(byte) 0x77, (byte) 0xf0, (byte) 0x50, (byte) 0x51,
(byte) 0x5c, 0x73, (byte) 0xfc, (byte) 0xf9, (byte) 0xf2 };
// IV 16 bits (préfixe du cipherText)
byte[] ivBytes = new byte[] { (byte) 0x69, (byte) 0xdd, (byte) 0xa8,
(byte) 0x45, (byte) 0x5c, (byte) 0x7d, (byte) 0xd4,
(byte) 0x25, (byte) 0x4b, (byte) 0xf3, (byte) 0x53,
(byte) 0xb7, (byte) 0x73, (byte) 0x30, (byte) 0x4e, (byte) 0xec };
// Initialisation
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
// Mode
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
String originalText = "hello i am original";
// ///////////////////////////////ENCRYPTING
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] ciphered = cipher.doFinal(originalText.getBytes());
String cipherText = new String(ciphered,"UTF-8");
System.out.println("ciphered: " + cipherText);
// ///////////////////////////////DECRYPTING
cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.**init(Cipher.DECRYPT_MODE**, key, ivSpec);
byte[] plain = **cipher.doFinal(ciphered);**
originalText = new String(plain,"UTF-8");
System.out.println("plaintext: " + originalText);
}
I couldn't figure out what am I doing wrong.any help is deeply appreciated.
also is this proper way to encrypted some data this time I am trying to encrypt 4byte city pin code.
thank in advance
////
I made those changes n' it's working fine but what's the issue if I passes
cipherText.getByte() in cipher.init() function. Like
byte[] plain = cipher.doFinal(cipherText.getByte("UTF-8"));
n' Thanks for all your help.
For decryption you need to initialize the Cipher in DECRYPT_MODE. And also the byte[] to String conversion is not correct (See other answer).
You cannot convert the encrypted bytes to a String like that. "bytes" and "chars" are two entirely different things. remove the code which turns the bytes to a String and back again between encrypting and decrypting and your code should work (as pointed out in other answer, the second step should be using DECRYPT_MODE).
note that you need to be careful when using the platform character encoding to convert between bytes and chars/String, as this may be different on different platforms. this may cause problems if your data needs to move cross platform. it can also be lossy if your default platform encoding doesn't support all the characters in the text you are using.

Cipher.init() required for each message?

Assume two clients are exchanging secure messages back and forth.
Must this block be run every time for each message, or can any step(s) be done just once at start:
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
output = cipher.doFinal(content);
I guess to lend some context- although I don't (yet) understand the internals completely, it is my understanding that for security purposes it's important to change the IV for each message. So I think the answer to this question will depend on whether that step happens under the hood at the doFinal() stage or init()....?
You are correct: to be safe you need to use a new,random, IV for each message. This means you either need to recreate the cipher or randomly set the IV yourself for each subsequent message. The former is probably safer since if you change ciphers or modes, there maybe some other state you need to randomly set as well and reinitializing the cipher should handle all of it.
If you don't do this, you end up with the same rather bad bug SSL had with IV reuse.
Cipher.doFinal does not reset the cipher to a random IV. In fact, its far worse than that, it appears to reset the internal state to the same IV you started with. As shown by this code.
Cipher f = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
f.init(Cipher.ENCRYPT_MODE, key);
byte[] iv = f.getIV();
System.out.println(Arrays.toString(f.doFinal("hello".getBytes())));
System.out.println(Arrays.toString(f.getIV()));
System.out.println(Arrays.toString(f.doFinal("hello".getBytes())));
System.out.println(Arrays.toString(f.getIV()));
System.out.println( Arrays.equals(f.getIV(), iv)); // true

Categories