Java to Python RSA - java

I'm trying to encrypt a string from Java to Python, using the library Bouncy Castle J2ME on the client side and Python M2Crypto on the other.
Everything is pretty good, I can decrypt it properly, but the padding is the issue.
The M2Crypto lib gives me (as far as I can tell) only these Padding schemes:
no_padding = 3
pkcs1_padding = 1
sslv23_padding = 2
pkcs1_oaep_padding = 4
While the bouncy castle J2ME only provides:
NoPadding
OAEPWithAndPadding
PKCS5Padding
SSL3Padding
So, I can use NoPadding between both, but then the strings that get generated after decryption are filled with jumbled characters.
I'd really like to get the padding sorted out, but I don't know how to convert between padding schemes / if that's even possible.
Please help me figure this out, it's killing me!

Bouncy castle provides padding. If you want for example to make an RSA with PKCS1 padding you have to do this:
public static PKCS1Encoding create_rsa_public(RSAKeyParameters PublicKey){
RSAEngine engine=new RSAEngine();
PKCS1Encoding encrypto=new PKCS1Encoding(engine);
encrypto.init(true,PublicKey);
return encrypto;
}
That function will return you an RSA engine with PKCS1Encoding.

I'm not familiar with Bouncy Castle but I guess you somehow use RSAEngine which implements AsymmetricBlockCipher thus you should be able to use PKCS1 or not?
And there also seems to be OAEP support, which given the right parameters should also work.

Related

Java AES encryption similar to aesCryptoServiceProvider

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.

Confused about AES cipher version

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.

String encryption PHP/Java

So, for a specific project I need to be able to encrypt and decrypt Strings in the same way that are encrypted/decrypted in another PHP application. My application is a Grails app, so I will be writing code in Java. The way the Strings will be encrypted/decrypted on the PHP side is (example code, not necessarily functional):
<?
$input="textToBeEncrypted";
function encrypt($data, $key)
{
$cipher_alg = MCRYPT_DES;
$mode = MCRYPT_MODE_CBC;
return #mcrypt_encrypt($cipher_alg, $key, $data, $mode);
}
function decrypt($encrypted, $key)
{
$cipher_alg = MCRYPT_DES;
$mode = MCRYPT_MODE_CBC;
return #mcrypt_decrypt($cipher_alg, $key, $encrypted, $mode);
}
$key ="testKey";
$data=$input;
$result = decrypt($data, $key);
echo ">>" . $result . "<br>\n";
?>
So, I would like to be able to apply the same encryption/decryption in Java (or Groovy). I have found this example code, https://github.com/stevenholder/PHP-Java-AES-Encrypt/blob/master/security.java and I understand that if I manage to find the names of the algorithm and mode in Java, it should work. Unless if I am missing something... I navigated to the Java Standard Names page for encrypting algorithms, http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html, but I can't find the exact equivalent of what I have in the PHP code. Any ideas? Has any of you guys ever needed to do something similar?
Thanks,
Iraklis
The three main things to consider with encryption are the algorithm, the mode, and the padding. Those must be compatible between the encryption and decryption software for everything to work.
To start with, AES (Rijndael) is definitely recommended in favor of DES as the encryption algorithm. DES is not considered secure enough any longer. The Java code you posted a link to is using AES, so it definitely won't be compatible with the PHP code you are showing.
Plus, that Java code is using ECB for the mode which is also not recommended. ECB is easier since it doesn't require any handling of initialization vectors but that is also its downfall. The PHP code is using CBC which is recommended, although I don't see any explicit IV handling. Mcrypt will use an IV of all zeros in that instance, which isn't ideal at all.
Finally the Java code is using PKCS5 as the padding method, whereas the PHP code uses zero-padding. Those aren't compatible. The default provider that comes with Oracle's JDK doesn't support zero padding, however Bouncy Castle does (see section 5.0). That would require either using Bouncy Castle's API directly or using it as a JCE provider using one of the methods detailed at that link. The the string "DES/CBC/ZeroByte" should do the trick.
Of course, zero padding can be problematic if the data you are encrypting can end with a null byte.
I've answered a question similar to this question before here and provided code for encrypting in Java and decrypting in PHP in the answer. Hopefully that might help you.

Java equivalent of C++ encryption [duplicate]

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.

Symmetric Encryption between .NET and Java

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

Categories