Hello,
I'm trying to set up a process for our customers to encrypt a query
string on their end and we then decrypt it on our end. Our customers
use various platform/languages from Java to ASP.NET to PHP. Our application is in Rails.
I have been able to encrypt a string in PHP and Ruby and then successfully decrypt in Ruby. However, I am having a brutal time of it in Java. I think there may be something I am doing wrong when encoding in base64. I'm not sure. Below is how I have my code set up:
Encryption
$input = "lovingcare@newou";
$key = "dfopnhqs88421738";
$cipher_alg = MCRYPT_RIJNDAEL_128;
print "Original string: $input <br>";
$encrypted_string = mcrypt_encrypt($cipher_alg, $key, $input, MCRYPT_MODE_CBC);
$b64Encoded = base64_encode($encrypted_string);
print "Encrypted string: ".$b64Encoded."<br>";
When run, the above PHP code generates the following encrypted string for the $input provided: 7nBID895HfsZd0zYEftvAQ==
I am also encoding in Ruby as follows:
input = "lovingcare@newou"
rijndael = Crypt::Rijndael.new( key, 128, 128 )
encryptedBlock = rijndael.encrypt_block(input)
b64Encoded = Base64.encode64(encryptedBlock)
puts "Encrypted string: " +++ b64Encoded
When run, the above Ruby code generates the following encrypted string for the input provided: 7nBID895HfsZd0zYEftvAQ==
In both cases, the PHP and Ruby code generate the proper encrypted string which I am able to decrypt in Ruby.
Below is my Java code to encrypt:
import javax.crypto.*;*
import javax.crypto.spec.;
import java.security.;
import java.io.;
import java.util.prefs.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import com.Ostermiller.util.Base64;
class test {
public static void main(String[] args) throws Exception {
String plaintext = "lovingcare@newou";
String key = "dfopnhqs88421738";
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE,keyspec);
byte[] encrypted = cipher.doFinal(plaintext.getBytes());
BASE64Encoder base64 = new BASE64Encoder();
String encodedString = base64.encodeBuffer(encrypted);
System.out.println("Ostermiller Encrypted 64: " Base64.encodeToString(encrypted));
System.out.println("sun.misc Encrypted 64: " encodedString);
}
}
When run, the above Java code generates the following encrypted string for the input provided: 7nBID895HfsZd0zYEftvAYRelNu/8ddiENq1SDhyA+o=
Any idea why I am getting all these extra characters. As you can see, the encrypted string generated by Ruby and PHP is similar to the Java encrypted string for the first 21 characters.
Any suggestions?
Thanks,
-J