RSA ENCRYPTION IN ANDROID AND DECRYPTION IN SERVER SIDE - java

I have made a https api request from android to server. The API request contains one parameter that needs to be encrypted before it is send (i.e. it's a password). RSA/ECB/PKCS1Padding is the encryption used in both end.
Encryption in android side does the following things:
/*Encrypt the password using public key.public key is obtained from generateRsaPublicKey(BigInteger modulus, BigInteger publicExponent) function)*/
public static String rsaEncrypt(String originalString, PublicKey key) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherByte = cipher.doFinal(original);
return bytesToHex(cipherByte);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//generate public key with given module and exponent value
public static PublicKey generateRsaPublicKey(BigInteger modulus, BigInteger publicExponent) {
PublicKey key = null;
try {
key = KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
return key;
} catch (Exception e) {
Log.e("error", e.toString());
// return null;
}
return key;
}
// Helper methods
final protected static char[] hexArray = "0123456789abcdef".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
// Log.d("byte array representaion","value in integrer"+v);
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
below is the source for decrypting the password on the server
// *** setup private key
RSAPrivateKeySpec privateRPKS
= new RSAPrivateKeySpec(new BigInteger(gModulusPlainS, 16), new BigInteger(privateExponentPlainS, 16));
KeyFactory keyFactoryKF = KeyFactory.getInstance("RSA");
RSAPrivateKey gPrivateKeyRPK = (RSAPrivateKey) keyFactoryKF.generatePrivate(privateRPKS);
// *** setup cipher
Cipher cipherC = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipherC.init(Cipher.DECRYPT_MODE, gPrivateKeyRPK);
// *** decrypt hex-encoded cipherTxS
byte[] baCipherText = hexToBin(cipherTxS.getBytes());
byte[] baPlainText2 = cipherC.doFinal(baCipherText);
String decryptedTextS = new String(baPlainText2);
But I got the following error log
javax.crypto.IllegalBlockSizeException: Data size too large
at com.ibm.crypto.provider.RSASSL.a(Unknown Source)
at com.ibm.crypto.provider.RSASSL.engineDoFinal(Unknown Source)
at javax.crypto.Cipher.doFinal(Unknown Source)
javax.crypto.BadPaddingException: Not PKCS#1 block type 2 or Zero padding
But it is working on websight part. Why it isn't working in android?
Thank you for your kindness to looking my code.

You are sending the ciphertext as string, if cipherTxS.getBytes() is indeed a string to byte array conversion. Ciphertext should be either kept in binary or possibly encoded using base 64 encoding.

Thanks to Alex Klyubin, Android Security Engineer. I have got answer from Here
Developers who use JCA for key generation, signing or random number generation should update their applications to explicitly initialize the PRNG with entropy from /dev/urandom or /dev/random.Also, developers should evaluate whether to regenerate cryptographic keys or other random values previously generated using JCA APIs such as SecureRandom, KeyGenerator, KeyPairGenerator, KeyAgreement, and Signature.
Code comment: Install a Linux PRNG-based SecureRandom implementation as the default, if not yet installed.This is missing from jellybean onwards.
Sample code implementation

Related

Java Encryption Conversion from .NET

I was given this .NET code and I need to convert it to Java. I have found a bunch of articles but nothing I try works.
public string EncryptNVal(string vVal, string accountNumber, string sharedSecret)
{
byte[] IV = Convert.FromBase64String(vVal);
byte[] Key = Convert.FromBase64String(sharedSecret);
SymmetricAlgorithm sa = Rijndael.Create();
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, sa.CreateEncryptor(Key, IV),
CryptoStreamMode.Write))
{
byte[] data = Encoding.UTF8.GetBytes(accountNumber);
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
ms.Position = 0;
return Convert.ToBase64String(ms.ToArray());
}
}
This is some of my attempt which you can guess throws exceptions.
public String EncryptNVal(String vVal, String accountNumber, String sharedSecret) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
byte[] IV = Base64.decodeBase64(vVal);
byte[] Key =Base64.decodeBase64(sharedSecret);
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
KeySpec keySpec = new PBEKeySpec(Base64.decodeBase64(sharedSecret).toString().toCharArray());
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = factory.generateSecret(keySpec);
PBEParameterSpec paramSpec = new PBEParameterSpec(IV,salt,1000);
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
byte[] ciphertext = cipher.doFinal(accountNumber.getBytes(StandardCharsets.UTF_8));
return Base64.encodeBase64String(ciphertext);
In the same project I have this code which I think I got correct, but any confirmation on that would be helpful as well.
.NET code I was given
public string GetMd5Hash(string input)
{
using (var md5Hash = MD5.Create())
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
var sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
foreach (var t in data)
{
sBuilder.Append(t.ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
}
What I wrote in Java:
public String GetHash(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] inputBytes = input.getBytes("UTF-8");
md.update(inputBytes);
byte inputHash[] = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < inputHash.length; i++) {
hexString.append(Integer.toHexString(0xFF & inputHash[i]));
}
return hexString.toString();
}
On a side note I can use either MD5 or SHA256, the .NET code was using MD5, so I was trying to follow that since my knowledge of encryption is about null. I am willing to use the SHA256 if someone can give me good advice.
I took me some time, and a lot of errors to figure this out, but here's a java method which yields exactly the same output as your C# method.
I'm no expert at all in crypto stuff, but this seems to do the work.
public static String EncryptNVal(String vVal, String accountNumber, String sharedSecret){
try {
byte[] vValAsBytes = java.util.Base64.getDecoder().decode(vVal);
byte[] sharedSecretAsBytes = java.util.Base64.getDecoder().decode(sharedSecret);
byte[] accountNumberAsBytes = accountNumber.getBytes();
SecretKeySpec key = new SecretKeySpec(sharedSecretAsBytes, "AES");
IvParameterSpec iv = new IvParameterSpec(vValAsBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] output = cipher.doFinal(accountNumberAsBytes);
String signature = java.util.Base64.getEncoder().encodeToString(output);
return signature;
}
catch(Exception e){
e.printStackTrace();
return "<dummy>";
}
}
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
A few additional info :
Rijndael is not AES, in the sense that it's not implementing the actual AES standard. If this is for production use, I'd suggest moving to actual AES (take a look at this link for info).
AES/CBC/PKCS5Padding is the closest match I could find for C#'s Rijndael . Although C# seems to use PKCS7, this doesn't seem available for Java (at least not on my system). PKCS5Padding yields the same result, but it will probably not work in 100% of the cases.
It only required trial and error, no deep knowledge of either C# or Java. You'll probably face similar challenges (or related problems which will be induced by your particular use case), and I'd suggest you apply a similar workflow as mine, when it comes to translating from a language to another :
Use and abuse of printing capabilities, to ensure all steps of both codes have the same state
Arrange the code with the same logical flow on both sides
Thoroughly read the documentation of your source function that you want to translate

WinCrypt RSA vs Java org.bouncycastle

So here is a question.
I have an old code on a Windows system that just takes a short string and makes CryptEncrypt on it with a public RSA key.
The minimum working example is here (avoiding any checks to make it shorter. avoiding freeing as well)
std::string testData = "12345678";
HCRYPTPROV context;
CryptAcquireContext(&context, nullptr, nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
auto pubK = FromBase64(PublicKey);
CERT_PUBLIC_KEY_INFO *pubKeyInfo = nullptr;
DWORD keyLength = 0;
CryptDecodeObjectEx(X509_ASN_ENCODING, X509_PUBLIC_KEY_INFO,
pubK.data(), pubK.size(),
CRYPT_ENCODE_ALLOC_FLAG, nullptr,
&pubKeyInfo, &keyLength);
HCRYPTKEY key;
CryptImportPublicKeyInfo(context, X509_ASN_ENCODING, pubKeyInfo, &key);
std::vector<std::uint8_t> result(testData.begin(), testData.end());
DWORD size = testData.size();
CryptEncrypt(key, NULL, true, 0, result.data(), &size, result.size());
result.resize(size);
size = testData.size();
CryptEncrypt(key, NULL, true, 0, result.data(), &size, result.size());
std::cout << ToBase64(result) << "\n";
The code works and returns a base64 encoded string. like lTq01sOcgDcgwtDaFFoHH/Qb6xLw0KU+/n/+3t0eEb8l4N69QGcaEWf1qso3a4qn7Y8StlXcfMe8uspNF/KDj6qQOMvCuM+uUl+tkLd5NXiESsjycgjyxAqdCIO71iTSmsYVcsS3fY/gtIbO4UAFnCRPOXoSyqWqpXW7IRtFzL2N3MxgIBlIMErNvNWs5HPA7xAY/XO6UpSMWsQO4ppccdeNLSZDPwOxohKD/BX5oDin81nFn7fvIZgghfH5knF1nezK8IGKl+vtbgrwlUUULp/wJ4POceyIn0HaZoVsaCu6xFJcUJGfBqSvm4GZqkp2MlGxBODku0OSgEfIDEGMTg==.
Then I have to decrypt this string with the private key on another side running java.
I use bouncycastle:
try {
Security.addProvider(new BouncyCastleProvider());
String value = "";
AsymmetricKeyParameter privateKey =
(AsymmetricKeyParameter) PrivateKeyFactory.createKey(Base64.getDecoder().decode(privateKeyValue));
AsymmetricBlockCipher e = new RSAEngine();
e = new org.bouncycastle.crypto.encodings.PKCS1Encoding(e);
e.init(false, privateKey);
byte[] messageBytes = Base64.getDecoder().decode(inputdata);
byte[] hexEncodedCipher = e.processBlock(messageBytes, 0, messageBytes.length);
value = new String(hexEncodedCipher);
System.out.println(value);
return value;
}
catch (Exception e) {
System.out.println(e);
}
And this code shows me the next error:
org.bouncycastle.crypto.DataLengthException: input too large for RSA cipher.
And I believe I'm missing something on the windows side, because if I use the same keys on the Java side and crypt the same data with the same public key, the decryption works as expected.
Here the keys, I generated with openssl for this question (RSA 2048):
Private:
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCeL7K++3+vl52Q
WFC6ThgvNPlhHLlP5ylIMi/7Gy60wcCHtx8R5Hzi2j7Kx/uBXyr7SCbePS7NtqHx
meVK3VhEvYHz2uYaUNf6GqJgNNjfRymnL5ll8K8lq1wym6A7KZ+L3qLHH1oI6GfW
+uf32nUfy1PQvsatPN7aiJ4ymiaJj2LcI6Bp78CINsu56Cx9QBN9uoXqKO/7NjOz
y2GRdYdckiqCkcmGDzA4/5tJROxj21gUbxwoUR+yz2sVFGlcJycsDDJiIXiPjbVN
XgM/YfmRjdAPQQwXXj9AK5w/dp9TPq621WqYES74rIY05cba4v1kihmFbs0DHLrV
fQZB0Pu9AgMBAAECggEAGuD//nO9vpiErYJUNVQPx/W4akf3NRySZzIf9QspZI2H
qYf0P5YTonhzMwHIOrNxGkGoWRsMWOgvnF4KGC6EUSniaw1HDDGwgU8FSFOyhj4R
VddAuZGsMTps8CyBjYwFED9EaZFqOxlCi8UWpYb5X+2s0EuadtVhCMEuIGsRIU53
mfW11182YtbAI7Zqi7wg/w0yRz5rVj4ph8nbSFPgi6qtVWA9bxVxNeRTXyQDWjUU
NFQzGcRG6D/SYTnRzTndVM5TmTwEVt0hvJNA2/pMWF5XMu6B2exOpJIVVVdQ40l/
XHh33SU8+gQYY56rHzFebCa0Nuxwdk0paluv+x3CAQKBgQDKwe8QXfNlMDqrM06n
iq/NwKE7tB+1gs1nKr4qZdbI71IzgQJgIJcxbJwbuE6z6Yk8PoancEELH9mSY7EN
YGeSO3QsO1LF1vyJWgWQU1G3pfC9sh8sY6f9WYg8+JogIeJsgjwf7PXrGaBq8++Q
GBMUATzPAh/ERIqUip0nEQ2IJwKBgQDHuYgPvv77qhLc+ZNOdhaZtibeVsFx50V+
a+qR+INSTJ/CChNkoVtMg803ZQWckJBOYL/TS2Mw+ctNomUg+ImjULGT9GzqMeme
HkPpAj5pNyNVpRfVNZfmS2cwwuRyE1QbFGs3C4p7D5MKKCfl4/8MBQXtJGWrQZFr
owh2NNyHewKBgHsMmSYorlcBnwlZOOnK7AiFWBRgq0G/4SI0OXaHmYMWYp+pMqTe
AoPXMyJLh0/+ce/izlt9b6vtp2AFKmVA1XpUpJtXYVN5tocw3+GH/zbh+SlWmT6a
OFAz7s953CeWCNDrdMu3RkNoqQdfhUrAoYtpeNr0ogy9wBCH0vnrinfPAoGBALNy
U/hpz+lH1qjqKFsPqKC001ljM21msL60sU4zrbHNHKEXsnLwsvodVc3Wm2MfVDjH
nrJ2gomnde2r4hbsl6W/w70+mHkXHWKuqK97D54zJzE1IyOygmctCmr6QIzqJuAp
yWbsnKCSzrcKe0aHQkmHXdrCoAJt5/2AvwKN3jJvAoGAIaLts1F7shIZ365FXyWD
poOFtXsNRXESkcYpJ2Pn+K0fUNtdH4BtR/5Z5bsEWXBf2LbL7s15UZFZbck0KH3K
22BRgPQze7wEhMVFlIMNhF17WrOh2NTGUAVz2CYSthbYh0QSI+5XJk0AEfiQcqYk
+E4bZw/RUTY94V+ITEK6F8g=
public
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAni+yvvt/r5edkFhQuk4Y
LzT5YRy5T+cpSDIv+xsutMHAh7cfEeR84to+ysf7gV8q+0gm3j0uzbah8ZnlSt1Y
RL2B89rmGlDX+hqiYDTY30cppy+ZZfCvJatcMpugOymfi96ixx9aCOhn1vrn99p1
H8tT0L7GrTze2oieMpomiY9i3COgae/AiDbLuegsfUATfbqF6ijv+zYzs8thkXWH
XJIqgpHJhg8wOP+bSUTsY9tYFG8cKFEfss9rFRRpXCcnLAwyYiF4j421TV4DP2H5
kY3QD0EMF14/QCucP3afUz6uttVqmBEu+KyGNOXG2uL9ZIoZhW7NAxy61X0GQdD7
vQIDAQAB
What do I wrong?
CryptEncrypt returns the ciphertext in little-endian format, see CryptEncrypt( Remarks, last section). For the decryption in Java the byte array messageBytes must therefore be inverted, e.g. here.

on android, getting xml rsa public key and encrypt a string with it

I'm developing an android app and getting this public key from the server of the company that I work with:
PFJTQUtleVZhbHVlPjxNb2R1bHVzPnZOcFhkRWVOTU5pZDhuOTlUekRGMVo4MDNvTEdRSzlqWnNFODlDd2tiS29GV0tGZmt2QTZKODBNWHhPZnhqbFZIYU8vYWM4YUpMc1AxWVR1RFNHVis3VExQL0puVVpyNlJQQTdpbFlmMitVWExiS0U2ZW1RYzBKdXlOaVArL0FTMGZmKzYwSnZQekhYeEdQQnVIbWtTcmRqdEtFV0JCZXJzWWNuQVJyT2ZSYz08L01vZHVsdXM+PEV4cG9uZW50PkFRQUI8L0V4cG9uZW50PjwvUlNBS2V5VmFsdWU+
the server is windows with IIS 7.5.
base64decode it give me this XML
<RSAKeyValue><Modulus>vNpXdEeNMNid8n99TzDF1Z803oLGQK9jZsE89CwkbKoFWKFfkvA6J80MXxOfxjlVHaO/ac8aJLsP1YTuDSGV+7TLP/JnUZr6RPA7ilYf2+UXLbKE6emQc0JuyNiP+/AS0ff+60JvPzHXxGPBuHmkSrdjtKEWBBersYcnARrOfRc=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
Extracting the Modulu and the Exponent from this xml, base64decode them and making the spec for the public key object:
PublicKey pbKey = null;
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(publicKeyString);
Element rsakeyvalue = doc.getDocumentElement();
String modulusBase64 = parser.getValue(rsakeyvalue, "Modulus");
byte[] modulus = Base64.decode(modulusBase64, 0);
String exponentBase64 = parser.getValue(rsakeyvalue, "Exponent");
byte[] exponent = Base64.decode(exponentBase64, 0);
BigInteger modBigInteger = new BigInteger(1,modulus);
BigInteger exBigInteger = new BigInteger(1,exponent);
RSAPublicKeySpec spec = new RSAPublicKeySpec(modBigInteger, exBigInteger);
try {
KeyFactory factory = KeyFactory.getInstance("RSA");
pbKey = factory.generatePublic(spec);
} catch (Exception e) {
e.printStackTrace();
}
Creating the cipher and adding the plain text to encrypt with:
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
byte[] keyBytes = Base64.decode(this.publicKey, 0);
/* the strToPublicKey is the previews code block */
PublicKey publickey = strToPublicKey(new String(keyBytes));
cipher.init( Cipher.ENCRYPT_MODE , publickey );
// Base 64 encode removed.
//byte[] encryptedBytes = Base64.encode( cipher.doFinal(plainText.getBytes()), 0 );
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
everything here is working but the server don't accept it,
I'm base64 encode it and sending it as byte array.
the server admin saying it's too long, supposed to be 128 bit but it's 174 bit...
what I'm doing wrong?
How its called this key? RSA XML is correct? or it's got other name?
I can also get PEM string from the server if someone have an idea how to do it with it.
Edit:
i forgot to put here an important part, i'm sending the data to the server as byte array, this is how i make the string of it:
public static int unsignedToBytes(byte b) {
return b & 0xFF;
}
StringBuilder byteArrayString = new StringBuilder();
int bytesLength = bytes.length;
int bytesCounter = 0;
for (byte aByte : bytes) {
bytesCounter++;
byteArrayString.append(unsignedToBytes(aByte));
if(bytesCounter < bytesLength){
byteArrayString.append(",");
}
}
SOLVED! - the solution:
the bytes that the string builder used are signed so i use this function unsignedToBytes() to make them unsigned and i removed the base64Encription on the encrypt() function.
this was the problem, i hope it will help anyone else.
Your variable naming is bad. encryptedBytes contains not the encrypted bytes but the encrypted bytes in base64 encoding.
This is the reason you do not get the expected result.
The length of the encrypted data before applying Base64 encoding is 128 byte.
Afterwards the length is 172 bytes.

JAVA a reliable equivalent for php's MCRYPT_RIJNDAEL_256

I need to access some data that used PHP encryption. The PHP encryption is like this.
base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($cipher), $text, MCRYPT_MODE_ECB));
As value of $text they pass the time() function value which will be different each time that the method is called in. I have implemented this in Java. Like this,
public static String md5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Huh, MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Huh, UTF-8 should be supported?", e);
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
int i = (b & 0xFF);
if (i < 0x10) hex.append('0');
hex.append(Integer.toHexString(i));
}
return hex.toString();
}
public static byte[] rijndael_256(String text, byte[] givenKey) throws DataLengthException, IllegalStateException, InvalidCipherTextException, IOException{
final int keysize;
if (givenKey.length <= 192 / Byte.SIZE) {
keysize = 192;
} else {
keysize = 256;
}
byte[] keyData = new byte[keysize / Byte.SIZE];
System.arraycopy(givenKey, 0, keyData, 0, Math.min(givenKey.length, keyData.length));
KeyParameter key = new KeyParameter(keyData);
BlockCipher rijndael = new RijndaelEngine(256);
ZeroBytePadding c = new ZeroBytePadding();
PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(rijndael, c);
pbbc.init(true, key);
byte[] plaintext = text.getBytes(Charset.forName("UTF8"));
byte[] ciphertext = new byte[pbbc.getOutputSize(plaintext.length)];
int offset = 0;
offset += pbbc.processBytes(plaintext, 0, plaintext.length, ciphertext, offset);
offset += pbbc.doFinal(ciphertext, offset);
return ciphertext;
}
public static String encrypt(String text, String secretKey) throws Exception {
byte[] givenKey = String.valueOf(md5(secretKey)).getBytes(Charset.forName("ASCII"));
byte[] encrypted = rijndael_256(text,givenKey);
return new String(Base64.encodeBase64(encrypted));
}
I have referred this answer when creating MCRYPT_RIJNDAEL_256 method."
Encryption in Android equivalent to php's MCRYPT_RIJNDAEL_256
"I have used apache codec for Base64.Here's how I call the encryption function,
long time= System.currentTimeMillis()/1000;
String encryptedTime = EncryptionUtils.encrypt(String.valueOf(time), secretkey);
The problem is sometimes the output is not similar to PHP but sometimes it works fine.
I think that my MCRYPT_RIJNDAEL_256 method is unreliable.
I want to know where I went wrong and find a reliable method so that I can always get similar encrypted string as to PHP.
The problem is likely to be the ZeroBytePadding. The one of Bouncy always adds/removes at least one byte with value zero (a la PKCS5Padding, 1 to 16 bytes of padding) but the one of PHP only pads until the first block boundary is encountered (0 to 15 bytes of padding). I've discussed this with David of the legion of Bouncy Castle, but the PHP zero byte padding is an extremely ill fit for the way Bouncy does padding, so currently you'll have to do this yourself, and use the cipher without padding.
Of course, as a real solution, rewrite the PHP part to use AES (MCRYPT_RIJNDAEL_128), CBC mode encryption, HMAC authentication, a real Password Based Key Derivation Function (PBKDF, e.g. PBKDF2 or bcrypt) and PKCS#7 compatible padding instead of this insecure, incompatible code. Alternatively, go for OpenSSL compatibility or a known secure container format.

RSA encryption and decryption of a long message in java

I want to use java standard library, and as much as I know, its functions inputs are limited. So I implemented two methods to this purpose. Here they are:
private byte[] RSAenc(String in) throws Exception {
Cipher c = Cipher.getInstance("RSA");
c.init(Cipher.ENCRYPT_MODE, privKey);
int l = in.length();
byte[] part;
byte[] result = new byte[(int)(64*java.lang.Math.ceil(l/20.0))];
int i = 0;
while(i*20+20<l) {
part = c.doFinal(in.substring(i*20,i*20+19).getBytes("UTF-8"));
System.arraycopy(part, 0, result, i*64, part.length);
i = i+1;
}
part = c.doFinal(in.substring(i*20,l-1).getBytes("UTF-8"));
System.arraycopy(part, 0, result, i*64, part.length);
return result;
}
private String RSAdec(byte [] in) throws Exception {
Cipher c = Cipher.getInstance("RSA");
c.init(Cipher.DECRYPT_MODE, privKey);
String result = "";
byte[] part = new byte[64];
int l = in.length;
int i = 0;
while(i+64<=l) {
System.arraycopy(in, i, part, 0, part.length);
result = result + new String(c.doFinal(part), "UTF-8");
i= i+64;
}
return result;
}
They work in this manner: for encryption I break the string to at most, 20 size substrings, and then use the Cipher to encrypt them. For decryption, I break byte array to 64 byte blocks, and apply Cipher decryption to them.
Is there already a function which do this? Or at least is there a neater solution? How safe is my approach? Is encryption result length (result.length) always 64 on all distributions of JRE?
Thanx,
RSA is suited to key encipherment, not bulk data encryption.
Instead of encrypting messages with RSA, most protocols generate a key for a symmetric cipher, like AES, and encrypt the message with that. Then, RSA is used to encrypt that symmetric key so that only the message recipient can recover it. The RSA-encrypted symmetric key is sent with the AES-encrypted message to the recipient.

Categories

Resources