Will Java Bouncy Castle Always Throw Exception when decrypt Plain text - java

I have a process in my system that will receive input either random plain texts or a ciphertexts. Since performance is not an issue, i'm planning to try decrypt all incoming input, with pseudo-code something like this:
//get the input, either a plain text, or cipher text 'in disguise'
//ex of plain text: "some text".getBytes()
byte[] plainText = getInput();
try {
//try to decrypt whatever it is. Using Bouncy Castle as the AES crypto engine
plainText = AESDecryptor.decrypt(HARDCODED_AES_KEY, plainText);
} catch(Exception ex) {
...
}
//do some process with the plain text
process(plainText);
I'm using AES for the encryption method.
The code above rely heavily on an assumption that trying to decrypt a plain text using bouncy castle will always throws exception. But is the assumption 100% correct? will it always throws exception when trying to decrypt plain, human readable text?
Thanks in advance!

Short answer
No, you cannot guarantee an exception.
Longer answer
The probability of receiving an exception is dependent upon the padding scheme used. When a cryptographic library decrypts data using an algorithm that includes padding, it expects to find correctly padded plaintext. If the padding is malformed (e.g. because the input was plaintext, not ciphertext) an exception is likely to be thrown.
If you are not using a padding scheme in your decryption and your input is a multiple of the block size of the cipher (in the case of AES - 16 bytes), then your library will happily decrypt plaintext and give you junk.
As an example, consider PKCS #7 padding. This appends a non-zero number of bytes to the end of the plaintext, with a value that is equal to the number of padding bytes. Sufficient bytes are added to align the plaintext with the block size of the cipher. For example:
12 34 56 78 9A BC DE F0 08 08 08 08 08 08 08 08
Where the 08 values are eight bytes of padding to align with the AES block size. So, if you decrypt some plaintext is it likely to result in valid padding? Probably not. But it could and so it is a sloppy way to design your system.
You need to add another layer to your proposed protocol to indicate whether the data is encrypted or not. It may also be useful at this point to specify the algorithm used, as this might give you more flexibility in the future to support additional algorithms.

Related

Why does Java crypto AES pad my plaintext message which is exactly 16bytes?

For example, if a message is 16-byte long:
String message = "AAAAAAAAAAAAAAAA"
byte[] plaintext = message.getBytes();//plaintext.length = 16
the output cyphtertext would be 32-byte long, which indicates there are 2 blocks here, and the second block has been padded.
Whereas, if a message is 15-byte long or shorter:
String message = "AAAAAAAAAAAAAAA"
byte[] plaintext = message.getBytes();//plaintext.length = 15
the output cyphertext would also be 16-byte long.
Since AES's block is 16-byte long, why 16-byte plaintext message would be divided into two blocks and be padded?
Thanks!
It actually depends on the encryption mode. Some modes do not require padding at all, but the modes that require padding do require that messages of a multiple of the block length include an additional block full of padding bytes, otherwise it becomes ambiguous if the data is padded or not.
Since some messages will be padded, the algorithm will always look at the last bytes and interpret them as padding information. So all messages must be padded, even those that are of a suitable length in the first place.
For example, if your padding scheme adds bytes which values is the number of missing bytes to fill the block, and your message ends with 01 or 02 02, 03 03 03, etc. You wouldn't know if it's padding or data.

How does PHP handle 32 byte keys for tripledes encryption

Apologies all - newbie at encryption - been googling for days and finally asking outright.
I need to use PHP to encrypt and decrypt data that is readable by a Java TripleDES "DESede/ECB/NoPadding" function.
In Java there is a double-length 32 character key e.g. "F4D5CBDF57FEEDCFA41FD6AFE7BCDFEA" which gets converted to bytes and which provides an encrypted result without any problems. (I don't have the code.)
In PHP, when the same key is attempted via mcrypt for a tripledes, ecb function call, there is a key-length error because the system expects a max of 24 characters.
What do I need to do to the key so that PHP will produce the same encrypted result as Java?
As NullUserException postulated: please convert the key from hexadecimals to binary before using it for your triple DES cipher. Your Java code must do the same thing; in Java a triple DES key must have either 24 bytes or 16 bytes (16 bytes is only supported for later versions of Java, previously you had to convert to 24 bytes by copying the first 8 bytes to the end to create an "ABA" DES key).
32 byte keys are never supported for triple DES. If you are using the horrible mcrypt libraries for PHP however, the key gets cut to the highest key size available. So instead of a fail-fast situation, PHP rather would have their users pull their hair out in frustration.

SHA256withRSA what does it do and in what order?

I'm a total newbie when it comes to cryptography and such things. I don't (and dont want to) know the details of the SHA256 and RSA. I "know" what they do, not how they do it, and for now that's enough.
I'm wondering what the "SHA256withRSA"-algorithm (if you can call it that) actually do and in what order. For example, does it hash the data with SHA256 and then encrypts it using RSA or is it vice-versa, or something else?
The reason I'm asking is because I wanna do the java equivalent of:
Signature.getInstance("SHA256withRSA")
signature.initSign(privateKey); //privateKey == a key extracted from a .p12 file
in Objective-C on iOS. And I couldn't seem to find any stuff that does exactly this, therefore I'm asking, can I just hash the data (SHA256) and then encrypt it (RSA) (or vice-versa) and get the same behavior?
What is the suggested solution for doing this kind of thing?
Thank you!
EDIT:
I failed to mention that I sign the data using a private key that is obtained by doing:
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(new FileInputStream(new File(filename)), password.toCharArray());
PrivateKey privateKey = (PrivateKey)keystore.getKey(alias, password.toCharArray());
Where filename is for example: "/somewhere/mykey.p12".
"SHA256withRSA" implements the PKCS#1 v1.5 padding and modular exponentiation with the formal name RSASSA-PKCS1-v1_5 after calculating the hash over the data using SHA256.
So the general order is:
hashing;
padding the hash for signature generation;
modular exponentiation using the private exponent and the modulus.
The padding used for encryption and signature generation is different, so using encryption may result in erroneous signatures.
The PKCS#1 v1.5 padding scheme has been superseded by PSS. For new protocols it is advisable to use the PSS scheme instead. For RSA a very readable public standard exists. This standard has also been used as a base for RFC 3447: Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1 (which is basically a copy).
With regards to the padding in iOS, please check this answer by Thomas Pornin. Basically you should create the SHA-256 hash, prefix a static block of data (defined in the PKCS#1 specifications) then use SecKeyRawSign using kSecPaddingPKCS1.
For your convenience, the PKCS#1 defined block of data that needs to be prefixed in hex notation for SHA-256 (it can be bit hard to find in the standard documents, it's in the notes of section 9.2):
30 31 30 0D 06 09 60 86 48 01 65 03 04 02 01 05 00 04 20
Notes:
The above steps do not include the conversion from bytes to integer and vice versa. The result of raw RSA operations are generally converted to an unsigned big endian encoding with the same size of the modulus in bytes (which is generally the same as the key size, as the key size is already a multiple of 8). These conversions are called I2OSP and OS2IP in the RFC's.

DES encryption plain vs. cipher length

I am using Java to make a toy program that encrypts a message using DES encryption. The message I want to encrypt is:
String msg="This is a secret message";
Which I convert to bytes as:
byte [] msgBytes=msg.getBytes();
And send it to encrypt function that works as follows:
//encryption function
public static String encryptMsg(byte [] msgBytes, SecretKey myDesKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
Cipher desCipher;
// Create the cipher
desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] textEncrypted = desCipher.doFinal(msgBytes);
// converts to base64 for easier display.
byte[] base64Cipher = Base64.encode(textEncrypted);
return new String(base64Cipher);
} //end encryptMsg
Then, I display the cipher, the cipher and plaintext lengths and I get:
Encrypted Message: FDCU+kgWz25urbQB5HbFtqm0HqWHGlGBHlwwEatFTiI=
Original msg length: 24
Encrypted msg length: 44
Can you please clarify to me why the cipher length is 44 while the original message length is 24?
EDIT:
Kindly, I need the answer with clarification. The cipher always ends with =. Could this be because of the padding? Can you explain to me why/how the cipher is resulted with this length? And always ends with =?
Is my code correct or there is a mistake? I have doubts in the encoding part.
There are several things going on:
msg.getBytes() returns the bytes representing an encoding of the string using the "platform's default charset" (e.g. could be UTF-8 or UTF-16 or ..): specify the encoding manually to avoid confusion! In any case, see msgBytes.length to get the true plain text length.
DES, being a block cypher, will have output padded along a block size boundary - but this will always be larger than the plain text (refer to msgBytes.length) length when using PKCS#5 because the plain text is always padded with [1,8] bytes. To see what the true encrypted size is, see textEncrypted.length.
The encrypted bytes are encoded using base-64 and this process - which is independent of the encryption - inflates the number of bytes required by about 33% (as only 6 bits per character/byte are used). The Java base-64 implementation also adds padding which is where the trailing "=" character is introduced.
As long as you (or someone else with the correct algorithm and cipher key) can retrieve the initial string - by performing the inverse of each step in reverse order, then it works. If a particular step does not have an inverse/reverse operation or cannot be "undone", then something is wrong; but this also means that every step can be individually tested.
To the numbers!
msg.getBytes() returns an ASCII/UTF-8 encoded sequence (if it used UTF-16 or another another "wide" encoding then the numbers below would be too large)
Therefore, msgBytes.length is 24
And since msgBytes.length mod 8 is 0, the plain text is padded with 8 bytes that have the value of 0x08 (per CKCS#5)
Thus, textEncrypted.length is 32 (24 data + 8 padding)
Due to base-64 encoding, 32 bytes * 1.33 ~ 43 characters
And with base-64 padding (=), the final result is 44 characters!
The result of a DES encryption will always be a multiple of 8 bytes. The input is also padded to a multiple of 8 bytes according to the padding algorithm specified.
The base 64 encoding encodes each 3 bytes into 4 characters (3x8 = 4x6 = 24), and ensures the output length is a multiple of 4 by padding with = characters.
So, the 44 characters output corresponds to 33 bytes, but the = at the end indicates that in fact there were only 32 bytes. Which is fine, since 24 bytes clear data with PKCS5 padding becomes 32 bytes.

Java - Converting string into DES key

I have been given a key as a string and an encrypted file using DES. That is all I know. I don't know how the key was encoded.
There is also a des.exe that I can use to decrypt, this is all I found on the Internet: http://knowledge-republic.com/CRM/2011/07/how-to-decrypt-extract-recreate-thecus-storage-firmware/
Using des.exe, the only command it works with is "-D", not "-d".
My goal is to use Java to do the same thing. I copied and pasted this from somewhere
String key = "blah";
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
System.out.println(desKey);
Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE
if (mode == Cipher.DECRYPT_MODE) {
cipher.init(Cipher.DECRYPT_MODE, desKey);
CipherOutputStream cos = new CipherOutputStream(os, cipher);
doCopy(is, cos);
}
and it doesn't work.
What are some other options in converting a string into a key?
Should probably add I'm a complete newb at cryptography.
The SunOS man page for des (which seems to be what your des.exe is based on?) indicates that they key is generated like this:
The DES algorithm requires an 8 byte key whose low order bits are assumed to be odd-parity bits. The ASCII key supplied by the user is zero padded to 8 bytes and the high order bits are set to be odd-parity bits. The DES algorithm then ignores the low bit of each ASCII character, but that bit's information has been preserved in the high bit due to the parity.
It also mentions that the initial IV is always zero'd out, no matter what mode you are running in
The CBC mode of operation always uses an initial value of all zeros
for the initialization vector, so the first 8 bytes of a file are
encrypted the same whether in CBC or ECB mode.
It also mentions that the padding used is such that the last byte is always a value from 0-7, indicating the number of padding bytes used. This is similar to PKCS5Padding, so perhaps that would work
Since the CBC and ECB modes of DES require units of 8 bytes to be
encrypted, files being encrypted by the des command have 1 to 8 bytes
appended to them to cause them to be a multiple of 8 bytes. The last
byte, when decrypted, gives the number of bytes (0 to 7) which are to
be saved of the last 8 bytes. The other bytes of those appended to the
input are randomized before encryption.
Based on the options you indicated you are using, it sounds like you are using DES/CBC/PKCS5Padding for the cipher.
I think that just leaves determining how to actually derive the key. I found this sample code on exampledepot which might work for you. I think you would just need to convert your string password into 8 bytes (1 byte per character, so no UTF encodings) then stuff it through the code in the example to derive the key. Its worth a shot anyway.
DES keys are 7 (apparently SunJCE uses 7?) or 8 bytes. Check if the string you have been provided is 7 or 8 bytes. If so, then the chances are good it's the raw key. If not, it could be encoded in some fashion. A giveaway for hex encoding would be a prefix of 0x or suffix of h, and all characters would be in the range 0-9,A-F. You can certainly convert from hex yourself or use some code on the web, but I usually use an Apache commons lib (http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Hex.html).
That said, this is really speculation and I'm not sure we can jump to the conclusion that it's a problem with the key alone. Do you have any other info on the purported encryption algorithm? If the executable you cited works with "-d" then it seems like the encryption is plain DES in CBC mode:
-b : encrypt using DES in ecb encryption mode, the defaut is cbc mode.
(there are multiple possible modes, see http://download.oracle.com/javase/1.4.2/docs/guide/security/jce/JCERefGuide.html#AppA)
I would try setting your cipher to "DES/CBC".
Then again, I'm not sure how to interpret this:
Default is tripple cbc
You may be able to use this snippet to tell what ciphers are available on your system: http://www.java2s.com/Code/Java/Security/ListAllProviderAndItsAlgorithms.htm
I had the same issue with C#. I solved it in the end. You can have a look at my answer here: DES Initialization Vector in C#
Generally, what des.exe does, is that it computes a checksum using DES. So each encryption step is using the previous result instead of advancing in the output array.

Categories