In Java ,I use Bouncy Castle encrypt data using padding:
Cipher cipher = Cipher.getInstance("RSA/ECB/NOPADDING");
The Base64 encoded result is :
AAAAAAAAAAAAAAAAA.....H6hBDxOrCI0K8fd13vOYtsKdo4SI3VZTa3...
Ant it won't change every time.
And in C++, I use OpenSSL library to encrypt data :
RSA_public_encrypt(rsa_len, (unsigned char *)str, (unsigned char*)p_en, p_rsa, RSA_NO_PADDING);
The Base64 encoded result is :
bxeeBPfFRJsLOzJLMS/qGKtDe1zPw8H491QsE+uuRRay6/ep69fqv386j8...
And it will change every time I run code.
I read Wiki and know RSA encryption is a deterministic encryption algorithm.
So the result of java is reasonable and my question is:
Is "AAAAAAAA..." padding is correct for no padding of java?
What has openssl done in C++ code to cause the result seems to have padding and time varying?
Update
I found that my java code is correct.
And When calling RSA_private_encrypt with RSA_NO_PADDING, the input must
have the same size as the RSA key modulus. .After I fill my input to 256 bytes , openssl can decrypt the java encrypt result.
So, the question become to:
What has openssl done to fill the input to reach the required length?
Update
At last, I don't have much time to research the OAEP in openssl.And the server use this unsafe way due to history problem. So I fill my input with byte 0.Just like:
This is input //<-----following many ASCII 0 char to reach 256 bytes length
But this will cause the output be the same. Any other code should prevent this in either server and client.
And it will change every time I run code.
Yes. That's due to Optimal Asymmetric Encryption Padding (OAEP).
If you send the same message twice, like Attack at dawn, your adversary who observes the message won't be able to learn anything (or make an educated guess) when he sees the message again. The property is known as semantic security or Ciphertext Indistinguishability (IND-CPA).
Here's a related talk by Dr. Matt Green on PKCS padding versus OAEP padding. Its very approachable: A bad couple of years for the cryptographic token industry.
Is "AAAAAAAA..." padding is correct for no padding of java?
Possibly. I believe its just a string of leading 0x00 bytes that have been Base64 encoded.
What has openssl done in C++ code to cause the result seems to have padding and time varying?
Its using OAEP.
So, the question become to:
What has openssl done to fill the input to reach the required length?
Its using OAEP.
The question may become: why is Java not using it because lack of OAEP means you could leak information for each message encrypted.
Related
Hi is it possible to encrypt the string with the certain length that i want? for example: i want to encrypt this string BI000001 to something like hex value A3D5F2ARD3(random) fixed it at 10 length. Therefore when user enter this value A3D5F2ARD3, system will based on this value and decrypt it to get back the value BI000001 .
is it possible to do this in java?
I tried a lot of method but all encrypted length are way too long.
I am not aware of any JDK built-in Java encryption method which provides this feature. Then again, I am not an encryption expert, but I guess such a custom feature won't be built in the JDK.
Maybe this discussion is also useful: https://crypto.stackexchange.com/questions/6098/is-there-a-length-preserving-encryption-scheme
Why do you want to preserve size of the string? maybe there is another solution for your problem.
Typically you would use a block cipher such as AES to encrypt data. Block ciphers (as their name suggest) work in blocks of data of a fixed size, for example AES works in blocks of 128 bits. If a block cipher encounters input smaller than the block size it pads it, which is likely why you are seeing the ciphertext larger than the plaintext.
If you want to preserve the length then consider Format Preserving Encryption as mentioned in this question.
This question already has answers here:
How to decrypt file in Java encrypted with openssl command using AES?
(4 answers)
Closed 6 years ago.
I have this following snippet from c++ code that is used for encryption:
EVP_CIPHER_CTX ctx;
const EVP_CIPHER * cipher = EVP_des_ede3_cbc();
unsigned char iv[EVP_MAX_IV_LENGTH];
unsigned char key[EVP_MAX_KEY_LENGTH];
String seed;
_config->get_value("crypto_seed", &seed); // uses the seed value from pimp config.
if (seed.is_empty())
{
return false;
}
EVP_BytesToKey(cipher, EVP_sha1(),
(unsigned char *) 0, // no salt
reinterpret_cast<unsigned char *>(const_cast<char *>(seed.chars())), seed.length(),
1, // hash passphrase just once.
key, iv);
EVP_CIPHER_CTX_init(&ctx);
EVP_CipherInit_ex(&ctx, cipher, (ENGINE *) 0, key,
iv,
1); // encrypt
what s the equivalent of the c++ encryption in java?
I see there is des algorithm, then i see sha1.
This is related to openssl encryption. But not sure what is the equivalent. essentially i would like the same output as c++ code generates.
i m asking the what s the equivalent of EVP_CIPHER_CTX or what s the name of the encrytion being used here so i can take it from there.
EDIT: not asking anyone to convert the code to java, just asking the corresponding package or class that would do the same.
The trickiest part of this is the EVP_BytesToKey part, which has been recreated before.
How to decrypt file in Java encrypted with openssl command using AES?
I've also got an object oriented version laying around here, if you are really not up to using that C-like code. For SHA-1, use SHA-1 instead of MD5...
As for the encryption, simply use "DESede/CBC/PKCS5Padding" as algorithm name for your Cipher.getInstance() method and you should be fine.
The code you are converting from uses the openssl library. It carries out a triple-DES encryption using an Initial Vector. The first thing you need to understand is exactly what it's doing (and preferably why).
Unfortunately the openssl documentation isn't terribly thorough (see here) ... though the O'Reilley book Network Security with OpenSSL is quite a bit better (it's a bit out of date, though).
Once you know what needs to be done, you shouldn't have much difficulty coding it in Java using the standard javax.crypto package.
The encryption being used is Triple DES with cipher block chaining
RSA page: source
A cryptographic identifier which indicates a 3DES EDE CBC symmetric
cipher.
It looks like EVP_CIPHER_CTX is the “context” structure that's containing the encryption (akin to an object), but the actual cypher being used is EVP_des_ede3_cbc — which would be "des-ede3-cbc" with OpenSSL.encrypt(…) and friends
EDIT: To answer the question (“the corresponding package”), generally you should probably use javax.crypto or (probably “better” for most purposes) bouncycastle (http://www.bouncycastle.org/). But OpenSSL bindings do also exist — just awkward to use and deploy.
I am using a 3rd party platform to create a landing page, it is a business requirement that I use this particular platform.
On their page I can encrypt data and send it to my server through a request parameter when calling a resource on my site. This is done through an AES Symmetric Encryption.
I need to specify a password, salt (which must be a hex value) and an initialization vector (but be 16 characters).
Their backend is a .NET platform. I know this because if I specify an IV longer than it expects the underlying exception is:
System.Security.Cryptography.CryptographicException: Specified initialization vector (IV) does not match the block size for this algorithm.
Source: mscorlib
So for example, on their end I specify:
EncryptSymmetric("Hello World","AES","P4ssw0rD","00010203040506070809", "000102030405060708090A0B0C0D0E0F")
Where the inputs are: plain text, algorithm, pass phrase, salt, and IV respectively.
I get the value: eg/t9NIMnxmh412jTGCCeQ==
If I try and decrypt this on my end using the JCE or the BouncyCastle provider I get (same algo,pass phrase, salt & IV, with 1000 iterations): 2rrRdHwpKGRenw8HKG1dsA== which is completely different.
I have looked at many different Java examples online on how to decrypt AES. One such demo is the following: http://blogs.msdn.com/b/dotnetinterop/archive/2005/01/24/java-and-net-aes-crypto-interop.aspx
How can I decrypt a AES Symmetric Encryption that uses a pass phrase, salt and IV, which was generated by the .NET framework on a Java platform?
I don't necessarily need to be able to decrypt the contents of the encryption string if I can generate the same signature on the java side and compare (if it turns out what is really being generated here is a hash).
I'm using JDK 1.5 in production so I need to use 1.5 to do this.
As a side note, a lot of the example in Java need to specify an repetition count on the java side, but not on the .NET side. Is there a standard number of iterations I need to specify on the java side which matches the default .NET output.
It all depends on how the different parts/arguments of the encryption are used.
AES is used to encrypt bytes. So you need to convert the string to a byte array. So you need to know the encoding used to convert the string. (UTF7, UTF8, ...).
The key in AES has some fixed sizes. So you need to know, how to come from a passphrase to an AES key with the correct bitsize.
Since you provide both salt and IV, I suppose the salt is not the IV. There is no standard way to handle the Salt in .Net. As far as I remember a salt is mainly used to protect against rainbow tables and hashes. The need of a Salt in AES is unknown to me.
Maybe the passphrase is hashed (you did not provide the method for that) with the salt to get an AES key.
The IV is no secret. The easiest method is to prepend the encrypted data with the IV. Seen the length of the encrypted data, this is not the case.
I don't think your unfamiliarity of .Net is the problem here. You need to know what decisions the implementer of the encryption made, to come from your parameters to the encrypted string.
As far as I can see, it is the iteration count which is causing the issue. With all things the same (salt,IV,iterations), the .Net implementation generates the same output as the Java implementation. I think you may need to ask the 3rd party what iterations they are using
I've tried but failed to encode a string in Javascript to decode on a java server. We'd like to use the bouncycastle algorithm PBEWITHSHA256AND256BITAES-CBC-BC to decode serverside.
I've tried using crypto.js to do the encoding using the following code:
var encrypted = Crypto.AES.encrypt("it was Professor Plum in the library with the candlestick",
key,
{ mode: new Crypto.mode.CBC });
var encryptedString = Crypto.util.bytesToHex(Crypto.charenc.Binary.stringToBytes(crypted));
However this doesn't decode correctly on the server, my guess is its something to do with the SHA256 but I can't work out what it would be digesting & can't find any documentation. Does anyone know how to perform the encryption in javascript?
You need to do everything the same at both ends. You need the same key. You need the same mode (CBC) you need the same padding (use PKCS7) and you need the same IV.
Check that the actual key you are using is the same at both ends by displaying the hex, after you have run the passphrase through SHA-256. Check the hex for the IVs as well. Don't use any defaults, but explicitly pick the mode and padding to use.
If you think that it is the PBE/SHA-256 that is going wrong then you might want to look at how your text passphrase is being turned into bytes. Again, check the hex at both sides before it is passed to SHA-256. Converting text to bytes is a common source of errors. You need to be very sure what stringToBytes() is doing and that whatever you are using on the Java side is doing exactly the same.
Talking about javax.crypto.Cipher
I was trying to encrypt data using Cipher.getInstance("RSA/None/NoPadding", "BC") but I got the exception:
ArrayIndexOutOfBoundsException: too much data for RSA block
Looks like is something related to the "NoPadding", so, reading about padding, looks like CBC is the best approach to use here.
I found at google something about "RSA/CBC/PKCS#7", what is this "PKCS#7"? And why its not listed on sun's standard algorithm names?
Update:
I'm wondering, if is a padding problem, why this example run just fine?
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
/**
* Basic RSA example.
*/
public class BaseRSAExample
{
public static void main(
String[] args)
throws Exception
{
byte[] input = new byte[] { (byte)0xbe, (byte)0xef };
Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC");
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
// create the keys
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
new BigInteger("d46f473a2d746537de2056ae3092c451", 16),
new BigInteger("11", 16));
RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(
new BigInteger("d46f473a2d746537de2056ae3092c451", 16),
new BigInteger("57791d5430d593164082036ad8b29fb1", 16));
RSAPublicKey pubKey = (RSAPublicKey)keyFactory.generatePublic(pubKeySpec);
RSAPrivateKey privKey = (RSAPrivateKey)keyFactory.generatePrivate(privKeySpec);
// encryption step
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherText = cipher.doFinal(input);
// decryption step
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] plainText = cipher.doFinal(cipherText);
}
}
Update 2:
I realized that even if I use just Cipher.getInstance("RSA", "BC") it throws the same exception.
If you use a block cipher, you input must be an exact multiple of the block bit length.
In order to encipher arbitrary length data, you need first to pad you data to a multiple of the block length. This can be done with any method, but there are a number of standards. PKCS7 is one which is quite common, you can see an overview on the wikipedia article on padding.
Since block cipers operate on blocks, you also need to come up with a way of concatenating the encrypted blocks. This is very important, since naive techniques greatly reduce the strength of the encryption. There is also a wikipedia article on this.
What you did was to try to encrypt (or decrypt) data of a length which didn't match the block length of the cipher, and you also explicitly asked for no padding and also no chaining mode of operation.
Consequently the block cipher could not be applied to your data, and you got the reported exception.
UPDATE:
As a response to your update and GregS's remark, I would like to acknowledge that GregS was right (I did not know this about RSA), and elaborate a bit:
RSA does not operate on bits, it operates on integer numbers. In order to use RSA you therefore need to convert your string message into an integer m: 0 < m < n, where n is the modulus of the two distinct primes chosen in the generation process. The size of a key in the RSA algorithm typically refers to n. More details on this can be found on the wikipedia article on RSA.
The process of converting a string message to an integer, without loss (for instance truncating initial zeroes), the PKCS#1 standard is usually followed. This process also adds some other information for message integrity (a hash digest), semantical security (an IV) ed cetera. With this extra data, the maximum number of bytes which can be supplied to the RSA/None/PKCS1Padding is (keylength - 11). I do not know how PKCS#1 maps the input data to the output integer range, but
my impression is that it can take any length input less than or equal to keylength - 11 and produce a valid integer for the RSA encryption.
If you use no padding, your input will simply be interpreted as a number. Your example input, {0xbe, 0xef} will most probably be interpreted as {10111110 +o 11101111} = 1011111011101111_2 = 48879_10 = beef_16 (sic!). Since 0 < beef_16 < d46f473a2d746537de2056ae3092c451_16, your encryption will succeed. It should succeed with any number less than d46f473a2d746537de2056ae3092c451_16.
This is mentioned in the bouncycastle FAQ. They also state the following:
The RSA implementation that ships with
Bouncy Castle only allows the
encrypting of a single block of data.
The RSA algorithm is not suited to
streaming data and should not be used
that way. In a situation like this you
should encrypt the data using a
randomly generated key and a symmetric
cipher, after that you should encrypt
the randomly generated key using RSA,
and then send the encrypted data and
the encrypted random key to the other
end where they can reverse the process
(ie. decrypt the random key using
their RSA private key and then decrypt
the data).
RSA is a one-shot asymmetric encryption with constraints. It encrypts a single "message" in one go, but the message has to fit within rather tight limits based on the public key size. For a typical 1024 bit RSA key, the maximum input message length (with RSA as described in the PKCS#1 standard) is 117 bytes, no more. Also, with such a key, the encrypted message has length 128 bytes, regardless of the input message length. As a generic encryption mechanism, RSA is very inefficient, and wasteful of network bandwidth.
Symmetric encryption systems (e.g. AES or 3DES) are much more efficient, and they come with "chaining modes" which allow them to process input messages of arbitrary length. But they do not have the "asymmetric" property of RSA: with RSA, you can make the encryption key public without revealing the decryption key. That's the whole point of RSA. With symmetric encryption, whoever has the power to encrypt a message also has all the needed information to decrypt messages, hence you cannot make the encryption key public because it would make the decryption key public as well.
Thus it is customary to use an hybrid system, in which a (big) message is symmetrically encrypted (with, e.g., AES), using a symmetric key (which is an arbitrary short sequence of random bytes), and have that key encrypted with RSA. The receiving party then uses RSA decryption to recover that symmetric key, and then uses it to decrypt the message itself.
Beyond the rather simplistic description above, cryptographic systems, in particular hybrid systems, are clock full of little details which, if not taken care of, may make your application extremely weak against attackers. So it is best to use a protocol with an implementation which already handles all that hard work. PKCS#7 is such a protocol. Nowadays, it is standardized under the name of CMS. It is used in several places, e.g. at the heart of S/MIME (a standard for encrypting and signing emails). Another well-known protocol, meant for encrypting network traffic, is SSL (now standardized under the name of TLS, and often used in combination with HTTP as the famous "HTTPS" protocol).
Java contains an implementation of SSL (see javax.net.ssl). Java does not contain a CMS implementation (at least not in its API) but Bouncy Castle has some code for CMS.
This error indicates that the input data size is greater than the key modulus size. You will need a bigger key size to encrypt the data. If changing the key length is not an option, alternatively you may need to investigate if you are really expecting that big input data.
RSA can only be used to encrypt, when the number of bits being used to encrypt is greater then the size of the thing you are tying to encrypt + 11 bytes
Public-Key Cryptography Standards - PKCS
Scroll down a bit and you'll see it. It's not an cypher algortihm (like RSA) or a cypher mode like CBC, but a description of the way the certificate is encoded as bytes (i.e., a data structure syntax). You can find the spec for it here.
PKCS#7 is listed (referring to your link). It's encoding is PKCS7
Description
A PKCS#7 SignedData object, with the
only significant field being
certificates.
Use java.security.cert.CertificateFactory or CertPath when using PKCS7.
RSA is a block cipher. It encrypts block of the same key size.
Therefore, BouncyCastle RSA gives an exception if you try to encrypt a block
which is longer than the key size.
That's all I can tell you so far.
You should not encrypt your data using RSA directly. Encrypt your data with a random symmetric key (i.e. AES/CBC/PKCS5Padding) and encrypt the symmetric key using RSA/None/PKCS1Padding.