Well I want to generate the AES key using java and mentioned is the specification based on ".NET" utility that need to follow while generating the key in JAVA program
Specification: "Generate AES key using AesCryptoServiceProvider with Mode = ECB, Padding = PKCS7, KeySize = 256 &
BlockSize = 128."
I researched a lot but didn't get similar things that can be used in Java to generate the AES key.
Can anyone please guide me how to move ahead with the same to create the AES key with above specification mentioned?
For an AES key either use random bytes obtained from a CSPRNG or derive the key from a passphrase with PBKFD2.
Do not use ECB mode in new work and update legacy work ASAP, it is not secure, see ECB mode, scroll down to the Penguin. Instead use CBC mode with a random IV, just prefix the encrypted data with the IV for use in decryption, it does not need to be secret.
Notes:
The Java base implementation limits the key size to 128-bits (which is fully secure), in order to use a larger key you need to you have to use Java Cryptography Extension:
Java 6 JRE, Java 7 JRE, Java 8 JRE
(Thanks to Robert for the versions info and links!)
AES only has one block size: 128-bits.
For Java see the Documentation Java Cryptography Architecture Reference Guide and in particular The Cipher Class.
Related
I am encrypting in ojb-c with SecKeyEncryptedData and trying to decrypt in Java with javax.Cipher and hitting a problem.
I recently moved to doing long blocks and have needed to use a symmetric encryption with the AES key encrypted with the asymmetric key pair. I am having problems decoding.
I have the iOS key kSecKeyAlgorithmRSAEncryptionPKCS1 working for asymmetric data matched with Cipher.getInstance("RSA/ECB/PKCS1Padding") in Java. This decodes the short blocks.
As I need to send longer blocks, and am trying to switch to kSecKeyAlgorithmRSAEncryptionOAEPSHA512AESGCM on iOS and it encrypts fine, but i cannot find the method to use in Cipher to decrypt it and do not understand if it needs to be done in 2 steps in the cloud in Java.
OBJ-C:
SecKeyAlgorithm algorithm = kSecKeyAlgorithmRSAEncryptionOAEPSHA512AESGCM;
NSData* cipherText = nil;
cipherText = (NSData*)CFBridgingRelease( // ARC takes ownership
SecKeyCreateEncryptedData(self.pubKey, algorithm,
(__bridge CFDataRef)data, &error));
Java:
try {
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, priv);
byte[] dog = decoder.decode(encString);
dec = cipher.doFinal(dog);
res = new String(dec);
} // handle errors
The decode obviously fails.
So my question is in 2 parts.
is there a Cipher type that will do the decode needed or do i need to break out the encrypted AES key and decrypt it first?
If i need to break it up, how long is that encrypted AES key part of the data block and, if you know the ciphers for that it would be fantastic.
is there a Cipher type that will do the decode needed
You may read the Cipher documentation. I believe you are looking for RSA/ECB/OAEPWithSHA-256AndMGF1Padding
I see the designation doesn't exacly match with the Obj-C name, but this is a common standard so it may worth a try
As I need to send longer blocks, and am trying to switch to kSecKeyAlgorithmRSAEncryptionOAEPSHA512AESGCM
You may try to search for "hybrid encryption". Asymmetric ciphers are VERY slow comparing to symmetric ciphers and intended to encrypt only limited amount of data.
Some implementation may encrypt longer data anyway (for each 256 bit input providing 2048 o 4096 bit output), Java will simply complain and stop
So proper encryption would be
encrypt data with a radom key (DEK - data encryption key) using a symmetric cipher
encrypt the DEK using an asymmetric public key
If the kSecKeyAlgorithmRSAEncryptionOAEPSHA512AESGCM would be not counterpart (compatible) with RSA/ECB/OAEPWithSHA-256AndMGF1Padding, you may still use the PKCS#1 1.5 padding (the old one) with this approach.
Edit: this asnwer may be useful when working with OAEP too RSA/ECB/OAEPWithSHA-256AndMGF1Padding but with MGF1 using SHA-256?
Java has a mode called RSA/ECB/OAEPWithSHA-256AndMGF1Padding. What does that even mean?
RFC3447, Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1, section 7.1.2 Decryption operation says Hash and MGF are both options for RSAES-OAEP-DECRYPT. MGF is it's own function, defined in Section B.2.1 MGF1 and that has it's own Hash "option" as well.
Maybe the Hash "option" in RSAES-OAEP-DECRYPT and MGF1 are supposed to be the same or maybe they're not, it is unclear to me. If they are then I guess when you have RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING that means sha256 should be used for both. But if they're not supposed to be the same then you could have sha256 used for RSAES-OAEP-DECRYPT and, for example, sha1 used for MGF1. And if that's the case then what function is sha256 supposed to be used for? And what hash algorithm is supposed to be used for the other function?
And what does ECB mean in this context? ECB is a symmetric block cipher mode. Electronic Code Book. Maybe it's supposed to mean how Java deals with plaintext's that are larger than the modulo? Like maybe splits the plaintext into chunks that are as big as the modulo and then encrypts each one with RSA and concatenates them together? I'm just guessing..
The default for OAEP is to use SHA-1 for MGF1 (but see the edit on the end of this answer). Note that the hash chosen doesn't have that much impact on the security of OAEP, so mostly it will be left to this default.
We can easily test this by testing it against "OAEPPadding" and OAEPParameterSpec:
// --- we need a key pair to test encryption/decryption
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024); // speedy generation, but not secure anymore
KeyPair kp = kpg.generateKeyPair();
RSAPublicKey pubkey = (RSAPublicKey) kp.getPublic();
RSAPrivateKey privkey = (RSAPrivateKey) kp.getPrivate();
// --- encrypt given algorithm string
Cipher oaepFromAlgo = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
oaepFromAlgo.init(Cipher.ENCRYPT_MODE, pubkey);
byte[] ct = oaepFromAlgo.doFinal("owlstead".getBytes(StandardCharsets.UTF_8));
// --- decrypt given OAEPParameterSpec
Cipher oaepFromInit = Cipher.getInstance("RSA/ECB/OAEPPadding");
OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-1"), PSpecified.DEFAULT);
oaepFromInit.init(Cipher.DECRYPT_MODE, privkey, oaepParams);
byte[] pt = oaepFromInit.doFinal(ct);
System.out.println(new String(pt, StandardCharsets.UTF_8));
The code will fail with a padding related exception if you substitute "SHA-256" for the MGF1 as parameter.
The reason why the extended algorithm is needed at all is compatibility with other Cipher algorithms. Code written for e.g. "RSA/ECB/PKCS1Padding" doesn't use any parameters, let alone OAEP parameters. So without the longer string OAEP cannot function as drop in replacement.
The mode of operation "ECB" doesn't mean anything in this context, it should have been "None" or it should have been left out completely. You can only encrypt a single block using the RSA implementation of the SunRSA provider.
If you want to encrypt more data, create a random (AES) symmetric key and encrypt that using OAEP. Then use the AES key to encrypt your specific data. This is called a hybrid cryptosystem as it uses both asymmetric and symmetric primitives to encrypt data.
Note that OAEP is not supported in JDK 7 (1.7) or earlier. OAEP is included in the implementation requirements for Java runtimes since Java 8:
RSA/ECB/OAEPWithSHA-1AndMGF1Padding (1024, 2048)
RSA/ECB/OAEPWithSHA-256AndMGF1Padding (1024, 2048)
Some protocols may require you to use SHA-256 or SHA-512 within the padding, as SHA-1 is being deprecated for most use - even if it is not directly vulnerable for this kind of purpose.
EDIT: this was written mostly with Java in mind. By now many other libraries seem to take a somewhat different approach and use the same hash for the (mostly empty) label and MGF1 - which does make more sense. If you have an invalid OAEP ciphertext you should first make sure that the right "default" is being used. It is impossible to wrong any library implementation for choosing their own default; in the end it is up to the protocol to define the hashes used. Unfortunately no mandatory default exists - which is especially a problem if protocol owners forget to fully specify a configuration for the algorithms.
I'm trying to implement AES256 encryption into an android app. Data is coming from a server encrypted, I've been using the Android library JNCryptor to decrypt the data. It successfully does this, but it's very slow. I wanted to try Facebook's Conceal library because it reports having faster encryption and decryption speeds. My first implementation was decrypting a string from the server with the Conceal library. My problem comes when I try to pass the byte[] of the encrypted string to the decrypt function in Conceal.
ByteArrayInputStream bin = new ByteArrayInputStream(Base64.decode(encStr, Base64.DEFAULT));
InputStream cryptoStream = null;
try {
cryptoStream = crypto.getCipherInputStream(bin, new Entity("test"));
...
The crash comes because the given cipher version, which is found by getting the first byte of the byte [] does not equal the expected Conceal cipher version number 1.
I then looked at the encryption side of Conceal and saw this is just a number set during the encryption.
To double-check I then looked over the JNCryptor source code and saw it sets and looks for Cipher Version numbers 2 and 3.
I guess my questions are: What is the significance of the Cipher Version number? Would I be able to get the Conceal library to decrypt this data or are they just encrypted in totally different ways?
They are completely unrelated. For instance, Conceal seems to use GCM mode of encryption (which includes authentication) and RNCrypt uses AES in CBC mode and HMAC for authentication. Besides that it uses passwords and PBKDF2 instead of keys directly (although implementations like JNCryptor may include shortcuts to use keys directly - thanks Duncan).
Both are relatively minimalistic proprietary cryptographic formats, and both use AES. That's where he comparison ends.
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