I'm using the jpbc java library to achieve the HIBE encryption in order to encrypt and decrypt a String data.
In this case, i found a function that's allowed me to get an Element from a String as it shown below and it make me able to encrypt & decrypt this Element :
private static void elementFromString(Element h, String s) throws NoSuchAlgorithmException
{
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] digest = md.digest(s.getBytes());
h.setFromHash(digest, 0, digest.length);
}
But now, i need a solution to get the string data from the Element after decryption or any other idea can help me.
Thank you
Hashing is not encrypting. SHA-1 is a one-way function, i.e. you can possibly guess the input given the output, but you cannot retrieve the input by any calculation.
To encrypt and decrypt you need a cipher. A cipher often consists of a block cipher and a mode of operation such as "AES/GCM/NoPadding". Kind of surprising, it is represented by the Java Cipher class.
You may need to generate a key or key pair and store it somewhere, such as a KeyStore.
Trying to perform crypto without understanding what you are doing may result in code that runs - eventually. However, the chances that it will be secure is minimal. First try and learn about the subject.
Note that calling getBytes on a String results in platform specific encoding. This can be fun if you switch platforms in the future. Explicitly specifying UTF-8 is a good idea.
Related
I have a situation where I need to first encrypt a message using a public key and vector, that is already provided. Also as per requirement I need to use SHA-2 as well. For now, I am assuming that I need to hash the encrypted message and then send to the server. I have two questions related to this
1. Is it wise to hash the encrypted message? Also, will sending the encrypted message and hashed value to the server be a good idea?
2. I have done a lot search on internet, but whenever I try to get some example of using AES 256 and SHA-2 together, I actually land up where the difference between the two is explained. Can any help me with some sample code?
Thanks in Advance!!!
Let's break down the stuff first.
Public Key Cryptography
Allows a given pair (Kpriv, Kpub) to be used on a cipher to encrypt and decrypt data.
Any data encrypted with Kpriv can only be decrypted with Kpub and any data encrypted with Kpub can only be decrypted with Kpriv.
A nice and well known example of a public key cipher is RSA.
Asymmetric cryptography requires extremely large keys in order to be secure, such that it's extremely slow to execute! You should never encrypt large amount of data with Asymetric keys cryptography. You can use it in the beginning of a connecition to exchange a symetric key Ks, though.
Symetric Key Cryptography
Allows a Ks to be used on a cipher to encrypt and decrypt data.
An example of a symetric cipher is AES. AES is in fact so versatile you can change lots of parameters, such as, (as you mention) the Blocksize which can be of 128, 192 or 256 bits. AES256 is the AES cipher configured with a blocksize of 256 bits.
The block size is what's used against the provided Ks to perform the actual encryption. Note that your data can be larger than the block size (the algorithm will still work, It'l simply reuse the same Ks). Simply reusing the key every block is known as ECB mode and can reveal patterns if your data is repetitive. An alternative is to use modes like CBC or CTR which rely on also using previous block data and XORing with the next block data, to eliminate such patterns. What mode should you use depends on your data.
Note that, according to your cipher mode, you eventually will need padding. I'm assuming you are already quite familiar with this terms when you asked that question.
Guarantees By Cryptography
Cryptography does guarantee that the encrypted data is confidential but that's just it. It does not give any other guarantees such as whether the data is authentic or whether it has been tampered with or not.
While tampering data will most likely result in unintelligible text even after decryption, in cryptography, there's no such thing as invalid plaintext. As such, you need some mechanism to know if your data is valid or not.
A secure hash algorithm such as SHA can help you know whether your decrypted data is valid or not.
However, for these purposes, you usually shouldn't directly use a Digest algorithm. Try to instead use a MAC. That MAC can use SHA256 algorithm but MAC's and Hashes are not exactly the same.
How To Do It In Practice
If all you want is confidentiality and tampering detection, you would use the cipher and digest (or hash) algorithm as such:
E ks ( SHA(data) || data )
Where E is a symmetric cipher, ks is the shared symmetric key, SHA(data) is the digest of data using a secure hash algorithm, || means concatenation and data is a byte array.
A more safer approach would be:
E ks ( MAC mk(data) || data )
Where mk is the MAC's secret key.
Now just search how to "java symetric cipher" and "java hash byte array" and use the two as I'm describing above.
I am new in security and I'm wondering if I can make my program better, like changing or adding something to make it better ( more secure )
(I have doubt from the program output)
Here is the output:
Encrypted Message: +g#þóv«5Ùû`ž
keybyte: [B#71e7a66b
Original string: Message
Original string (Hex): [B#2ac1fdc4
Here is the code:
public class AES {
public static void main(String ... args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
final String Algo="AES";
String key = "aaaaaaaaaaaaaaaa";
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
MessageDigest sha= MessageDigest.getInstance("SHA-1");
keyBytes=sha.digest(keyBytes);
keyBytes=Arrays.copyOf(keyBytes, 16);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, Algo);
Cipher cipher = Cipher.getInstance(Algo);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] ciphertext = cipher.doFinal("Message".getBytes());
System.out.println("Encrypted Message: " +new String(ciphertext));
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] original = cipher.doFinal(ciphertext);
String originalString = new String(original);
System.out.println("keybyte: "+keyBytes);
System.out.println("Original string: " + originalString + "\nOriginal string (Hex): " +original);
}
}
No, this code is pretty terrible:
Your key is fixed and a string that is then hashed. This looks to me like your key is actually supposed to be a password. A single hash is not enough to derive a key from a password. You need to use a strong hashing scheme like PBKDF2, bcrypt, scrypt and Argon2. Be sure to use a high cost factor/iteration count. It is common to choose the cost so that a single iteration takes at least 100ms. See more: How to securely hash passwords?
Always use a fully qualified Cipher string. Cipher.getInstance("AES"); may result in different ciphers depending on the default security provider. It most likely results in "AES/ECB/PKCS5Padding", but it doesn't have to be. If it changes, you'll lose compatibility between different JVMs. For reference: Java default Crypto/AES behavior
ECB mode is pretty bad. It's deterministic and therefore not semantically secure. You should at the very least use a randomized mode like CBC or CTR.
Without authentication you have the threat of not detecting (malicious) modifications of your ciphertexts. 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 through HMAC with a strong hash function such as SHA-256.
Because of these issues you should use a library instead. Try JNCryptor or this library.
There are at least two problems with your implementation:
Unless you specify otherwise, you are using AES in ECB mode. ECB mode is not secure regardless of what cipher is under the hood. There are a number of secure modes, but usually people implement CBC mode, which is accomplished by changing your Algo to "AES/CBC/PKCS5Padding" (which really is PKCS7 padding, Java just does not know better). Then, you need to choose an IV via SecureRandom() to encrypt this way. This OWASP example seems to do it right (FYI -- 99% of the implementations you will find on the web have security problems somewhere).
Your key is not a key, instead it is a password that is being turned into a key. You shouldn't be hardcoding this, but I assume you are doing that for proof of concept only. In any case, the problem is using a hash function such as SHA-1 to turn a password into a key is not a good decision because passwords tend to have low entropy and can be brute forced. For this reason, you should be using a function that is dedicated to resisting brute force when turning a password into a key. Such functions include pbkdf2, bcrypt, scrypt, and argon2. For more information, Troy Hunt (a .Net guy) gives a good overview on the problems with using something like SHA-1 (or anything from the SHA2 family for that matter) in this context.
The other thing to keep in mind is that encryption does not generally provide message integrity. What this means is that just because you have encrypted the data does not mean somebody cannot modify it, and your software will still decrypt the modified data without being aware that it is modified. If you need to know that your data was not modified, then you will need to add on something like HMAC, or else you will need to switch to a mode of operation such as GCM.
Finally, AES is an excellent choice for security. But you need to use it in the right mode, you need to implement it right, and you need to understand whether you need more than just encryption.
I am trying to send an encrypted text with each HttpResponse and when I get the next HttpRequest with the encrypted text, I decrypt it and do some stuff :) with it.
I am curious about the best practices surrounding the storage/retrievel of the keys and ivSpec's (or nonce's) in general, but specifically looking at the code posted by #sherif based on #VoidPointer 's suggestions in How to encrypt String in Java,
a) Do we have to initialize ivSpec with random bytes for each string that I want to encrypt?
b) If so, do we store the generated ivSpec in some db and look it up when I need to decrypt using that?
c) If so, how do we look it up? When an encrypted string needs to be decrypted how do we pick the correct ivSpec from db?
d) One suggestion is to send ivParameter along with the encrypted string! itself (which is probably what is happening with #sherif 's implementation!). If we chose to do so, how can I modify the class provided by #sherif to decrypt and separate the iv parameter and encrypted string instead of providing the iv parameter while initializing decrypt cipher?
A. If you do not change the vector, each time you encrypt the same string, you get the same encrypted result.
By changing the IV each time, you make it so that every single encrypted output looks different (even if it's the same input).
Think of it as a the "salt" you use when you are hashing a password.
so under normal circumstances it would be desirable to use a random iv.
B&C. You need to look the IV up, yes. But storing it into a DB isn't very useful. You already have a piece of information that you keep stored secretly: that's the password. IV is just here to increase randomness, no need to keep it, push it out with the output.
D. Sending it is the usual way to go.
One way is to concatenate it at the beginning of the ouput. (output = IV + encrypted data). Then before decrypting first split the input (IV = 32 first bytes of input) and decrypt the rest (crypt_data_to_decrpt = input after byte number 32)
Another way is to have a constant IV and a random part at the beginning:
you simply use a string of NUL byte as an IV.
Then you encrypt 32 bytes of pure random garbage
Then you encrypt your input. (When using a good encryption method, this should always produce a different encrypted output because the beginning was different).
For decryption, you use the same empty IV, then you decrypt everything. You ignore the 32bytes at the beginning. You split and only take the bytes after the 32nd. That's your decrypted output.
I'm using BouncyCastle to encrypt/decrypt some files using AES and PKCS5 padding in CBC mode :
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
Now two questions:
How can I check that the provided key for decrypting data is correct or not ?
How Can I check encrypted input is untouched (e.g. not changed by user using an HEX editor)?
Thanks
You can use an AEAD mode, like CCM or GCM, in place of CBC. These modes authenticate an encrypted message, so if the wrong key is used, or the cipher text has been altered, you can detect it. You wouldn't be able to distinguish these cases though.
There is support in Java 7's cryptography API for GCM, but the SunJCE provider that ships with Oracle's Java implementation doesn't support it yet. You can get support through third-party providers like BouncyCastle.
You can achieve the same things if you use additional cryptographic services, like a digital signature or message authentication code.
Encryption is not just about the algorithm and the encryption key, it's also a lot about
the system organization.
In general, you can't determine that the key is correct. Any key can be used to decrypt the
data that's supposed to be decrypted, but it's up to some other mechanism to tell you if that
is the "correct" result.
In general, you can't determine if the data to be decrypted is untouched, except through some
external check. It's a property of most encryption systems that changing any of the encrypted
data would change the decrypted output drastically, probably into something you'd interpret
as garbage.
You should add a MAC which first verifies the integrity of the message, and only then you should decrypt it. A common choice of MAC is HMAC with whatever hash function you prefer, such as SHA-2.
Instead of doing this yourself, it's often a good idea to use an authenticated cipher. AES-GCM is a common choice. But you need to be really careful to never reuse an IV in that case.
The JCE ciphers are usually very basic. If you need a full featured protection including integrity and key testing, you need to combine them. And as usual it is better to not device that yourself. So better opt for a more high level format like PKCS7/12 or PGP.
Depending on the Padding used some ciphers will give you a PaddingException when you try to decrypt it with the wrong key. For stronger integrity check I would use a padding consiting of HMAC bytes.
A pretty complete method is included in the JCE, it is the AESWrap algorithm. It requires padded data but will ensure integrity. It is best combined with a length byte as described in RFC 3537. Note, that this is only intended for smaller amounts of secrets (like symmetric keys). The RFC3537 padding is restricted to 255 bytes.
To use this with a password derived key, you can use this:
char[] pass = ... // your password
byte[] codeBytes = ... // up to 255 bytes you want to protect
// generate wrapping key from password
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecureRandom rand = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[16]; rand.nextBytes(salt);
SecretKey kek = f.generateSecret(new PBEKeySpec(pass, salt, 1000, 128));
kek = new SecretKeySpec(password.getEncoded(), "AES"); // convert into AES
// RFC3537 padding (lengthbyte)
byte[] wrappedCodeBytes = new byte[codeBytes + 1 % 8];
System.arraycopy(codeBytes,0,wrappedCodeBytes,1,wrappedCodeBytes.length);
paddedCodeBytes[0]=(byte)codeBytes.length;
byte[] pad = new byte[paddedCodeBytes.length - codeBytes.length -1]; rand.nextBytes(pad);
System.arraycopy(pad,0,paddedCodeBytes,codeBytes.length+1,pad.length);
// AESWrap is WRAP_MODE:needs a SecretKey
SecretKey paddedCodeKey = new SecretKeySpec(paddedCodeBytes, "RAW");
// now wrap the password with AESWrap kek is 128 bit
Cipher c = Cipher.getInstance("AESWrap"); // default IV
c.init(Cipher.WRAP_MODE, kek);
byte[] result = c.warp(paddedCodeKey);
The unwrapping is left for the reader as an exercise :) The example code uses 128bit keysize, since more entropy cant be expected from the PBKDF2 anyway.
Note that this will detect wrong passwords with high probability, and some critics will see this as a weakness of AESWrap.
Take a look at this tutorial on BC encryption, specifically the InitCiphers methods, and in detail at the second code block which specifies the actual type of cipher.
How can I check that the provided key for decrypting data is correct or not?
According to JCE Javadocs, specifically the constructor of Class SecretKeySpec:
This constructor does not check if the given bytes indeed specify a secret key of the specified algorithm. For example, if the algorithm is DES, this constructor does not check if key is 8 bytes long, and also does not check for weak or semi-weak keys. In order for those checks to be performed, an algorithm-specific key specification class (in this case: DESKeySpec) should be used.
Note that Interface KeySpec lists all implementing classes, basically a list of validation options.
How Can I check encrypted input is untouched (e.g. not changed by user using an HEX editor)?
Indeed. That's a good one. 'Input' is pretty generic. Do you mean the actual content to decrypt? Well, if it's munged I believe it will not decrypt properly. Does that make sense?
IFF you are talking about the case of a key with parity bits being altered, as described in item (6) at the Bouncy Castle FAQ, you will have to do an actual parity check on the key. Only the first 56 bytes of the key are used for the encryption ops, and the last 8 bytes are reserved for parity checking. So, essentially, the last part of the 'key' can be changed and the first part is still useful. To detect whether either the parity or the key have been altered, you would run a parity check. I found this little ditty on doing a parity check. And, for more info on how parity is set in these keys, see comments in the JDK7 Crypto Provider source for Class DESKeyGenerator by Jan Luehe (near bottom) which discuss parity setting.
I recently had some interaction with BC, and I hope this info helps.
I am reading about encryption and having a lot of difficulty understanding these 3 Java statements of an encryption program.
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
encrypted = cipher.doFinal(str.getBytes())
Can somebody help?
In simpler terms,
create a new Encrypting Device using the AES algorithm;
make it ready
get the bytes of the string str and encrypt them; return the result into the encrypted object, whatever that is.
what exactly did you not understand?
cipher = Cipher.getInstance("AES");
Get a Cipher object that can encrypt/decrypt using the AES algorithm. Java's cryptography code is a bit weird - instead of directly creating objects, you generally use a getInstance call with a String argument. (Note that "cipher" means "way of encrypting something".)
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
Tell the cipher that you would like to encrypt something (Cipher.ENCRYPT_MODE), and give it the encryption key skeyspec.
encrypted = cipher.doFinal(str.getBytes())
The way ciphers work is that you feed them chunks of byte data using the update method, which causes the cipher to accumulate the encrypted data within itself. For the final block of data, doFinal is used, which tells the cipher that the encryption process is done. A different method is needed because the cipher often has to pad out the data returned to a particular length. doFinal then returns the final bit of encrypted information.
However, if there is a single readily available chunk of data, you can just call doFinal and it will give you all the encrypted bytes at once. But this explains why the method is called doFinal, not say, "process".
So in summary, the code above creates an AES encryption engine, gives it an encryption key, then uses it to encrypt the String str into the byte array encrypted.
Note that cryptography is very tricky business and very easy to get wrong. There's all kinds of things you need warning about that I haven't touched on because my wrists hurt now. So I would heavily recommend you get a copy of Beginning Cryptography with Java - it's where I learned to understand this stuff.