I am new to Android and i am working on a client server based application.Here i need to use RSA algorithm for Encryption/Decryption.
The scenario is:
1.Server has to create a Private/Public key pair (PHP) and send Public key to Client(Android Application)
2.The client should encrypt the data using that Public key and send to server
3.Now server has to decrypt using Private Key.
In PHP, i used 'PhpSecLib' to create key pair.
This is the coding :
Server.php:
<?PHP
include 'Crypt/RSA.php';
$rsa = new Crypt_RSA();
extract($rsa->createKey(1024));
echo $publickey;
?>
Generated Public Key :
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLz4yAo1FTOLc6nijBCTv5iVnW
F6MxCeM5+RxY+29AXcpMWhlM9oES3ESIfWw6OzrrENDyqwY+kVzCj2bWYnEAyJXs
WOpvqT2XSCPplwZOnQQGm+DnAYJXEeOfgU5DI63fwdiGv4M2ph1VMMe6684sBZu1
HhJHuhsX2eibBR0/lQIDAQAB
Now in Java, i successfully received this public key and stored in a String.
Coding:
protected String doInBackground(Void... params)
{
try
{
URL url=new URL("http://10.0.2.2/Samples/Server.php");
URLConnection con=url.openConnection();
con.setDoOutput(true);
BufferedReader ip=new BufferedReader(new InputStreamReader(con.getInputStream()));
String tmp,res="";
while((tmp=ip.readLine())!=null)
{
res+=tmp;
}
return res; //res contains the public key
}
catch(Exception e)
{
return new String("Exception : "+e.getMessage());
}
}
I am using Bouncy castle provider (bcprov-jdk15on-151) in java.
Now i have no idea about how to convert this string into RSA public key.
Pls suggest some code snippets? and if the code needs improvements and corrections, pls correct it.
Thanks...
Supposing that you download your key correctly, you can use your key in base 64 encoding to generate a java.security.PublicKey with the follow code:
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
public class ParseRsaPublicKey {
public static void main(String[] args) throws Exception {
String yourKeyB64 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLz4yAo1FTOLc6nijBCTv5iVnW\n"+
"F6MxCeM5+RxY+29AXcpMWhlM9oES3ESIfWw6OzrrENDyqwY+kVzCj2bWYnEAyJXs\n"+
"WOpvqT2XSCPplwZOnQQGm+DnAYJXEeOfgU5DI63fwdiGv4M2ph1VMMe6684sBZu1\n"+
"HhJHuhsX2eibBR0/lQIDAQAB";
// create the key factory
KeyFactory kFactory = KeyFactory.getInstance("RSA", new BouncyCastleProvider());
// decode base64 of your key
byte yourKey[] = Base64.decode(yourKeyB64);
// generate the public key
X509EncodedKeySpec spec = new X509EncodedKeySpec(yourKey);
PublicKey publicKey = (PublicKey) kFactory.generatePublic(spec);
// now you can for example cipher some data with your key
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherData = cipher.doFinal("someData".getBytes());
System.out.println(new String(cipherData));
}
}
Hope this helps,
Related
I want to encrypt my password in angular side before sending it to Springboot API. My idea is to do:-
Generate public key and private key in java
Do a base64 encoding on both public key and private key
Use encoded public key in node (angular) side, this will be used for encryption
Use encoded private key in springboot rest api, this will be used for decryption
Below is my java code which generates, encrypts and decrypts password
RSAKeyPairGenerator.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class RSAKeyPairGenerator {
private static String privateKeyString = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALyR1WRqVBuvdmXmgrcZ4VMY4hIFTYt63NGEN9atlgnngNliMasvzBofnjRtk5mukezUKujtON6mPnAjKJoEDdiaw3Rk0hKvgW5MszyUBE5bLThexVLbi+nQYSf2GSvd0fjdZn6KjhgVOdbYe+JduU/iPD3/Ti5p+w3MewgZpy2RAgMBAAECgYAqWdqCXfsb6LF/u2C6PN7Faf5EK9q5q9NyXu6nkX70JIFk0U/0cZy2dUlz3vRafMGbXh9xBu5R2yaEyvCwfp6ZF26A8MbS/IaI53LMKmyclhES2f3tZLKUPkg6fntz+e6e/6oSDdQPHP3J2QrpuwzyW+UZJQmmYYj7f9sq/+dawQJBAOnkHWkLuIZNIgLzV0TuHA6fcOXrqrSlS1/Q0qLyaQEZOObocXDvWaCSP+8RXiqZSwAnMJbrGHQA5ULXLWI4GjkCQQDOZP6bfn2VV3m8JSlYL9Uz4TrRYb8Qe3/mohhMsyDB7Ua/6d9BV7JZgbYiXP0utobKVWLxD49OFMkgEs20qY4ZAkB4dJsQ9pBZ2m+hxWE0hsy8WzDxuKV504c2GX3hnaamgi7j/OIvn5UxNSDoJrGwjrIpqgVENF+rnqpz+g3Nf8dBAkBV/op+6yMUGFBmbe1eCwAAD7XcC6f6DBrsU1lgi7n4Uw6JY75bkViEJqFmi+wJjI94uj7xRZRl6g8qx+rhfUvxAkEArD1we6ZLTWz73D8z+4Boj7Su7b5LhfgvXVL5V4Zdog3X58pHK+dYppapDh5KjZZdor+y/6uz1PqIs2dmFy/xtQ==";
private static String publicKeyString = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8kdVkalQbr3Zl5oK3GeFTGOISBU2LetzRhDfWrZYJ54DZYjGrL8waH540bZOZrpHs1Cro7Tjepj5wIyiaBA3YmsN0ZNISr4FuTLM8lAROWy04XsVS24vp0GEn9hkr3dH43WZ+io4YFTnW2HviXblP4jw9/04uafsNzHsIGactkQIDAQAB";
private static PrivateKey privateKey;
private static PublicKey publicKey;
public void generateKeys() throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair pair = keyGen.generateKeyPair();
RSAKeyPairGenerator.privateKey = pair.getPrivate();
RSAKeyPairGenerator.publicKey = pair.getPublic();
}
public void readKeys() throws NoSuchAlgorithmException, InvalidKeySpecException {
KeyFactory kf = KeyFactory.getInstance("RSA");
byte [] encoded = Base64.getDecoder().decode(privateKeyString);
PKCS8EncodedKeySpec keySpec1 = new PKCS8EncodedKeySpec(encoded);
RSAKeyPairGenerator.privateKey = kf.generatePrivate(keySpec1);
encoded = Base64.getDecoder().decode(publicKeyString);
X509EncodedKeySpec keySpec2 = new X509EncodedKeySpec(encoded);
RSAKeyPairGenerator.publicKey = kf.generatePublic(keySpec2);
}
public static void main(String[] args) throws NoSuchAlgorithmException, IOException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException {
RSAKeyPairGenerator keyPairGenerator = new RSAKeyPairGenerator();
// Next line is for testing with encrypted text generated by nodejs code with genrated keys
// keyPairGenerator.generateKeys();
keyPairGenerator.readKeys();
System.out.println("-----Private----------");
System.out.println(Base64.getEncoder().encodeToString(privateKey.getEncoded()));
System.out.println("Encoding : "+ privateKey.getFormat());
System.out.println("----------------------");
System.out.println("-----Public----------");
System.out.println(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
System.out.println("Encoding : "+ publicKey.getFormat());
System.out.println("----------------------");
String secretMessage = "Test";
System.out.println(secretMessage);
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] secretMessageBytes = secretMessage.getBytes(StandardCharsets.UTF_8);
byte[] encryptedMessageBytes = encryptCipher.doFinal(secretMessageBytes);
// Next lines are for testing decryption with encrypted text generated by nodejs code with generated keys
// byte[] encryptedMessageBytes = "B��u���<⌂�lǚm0�W������1�%EN�7��‼��l��l�<�����k;�������GĦ9D8��Z��I�Oɺ♫��→P'�§�{k�Ɋ+-}?��rZ".getBytes();
// byte[] encryptedMessageBytes = Base64.getDecoder().decode("woboAUytDXJLlKm7zbqNdxVORG+kio9kZxvMPOHruQfxwNEx7SVFTsw3oeETqbRs4NZskjzO2Nzjyms73vv758Dcy0fEpjlEOKmrWuG62knOT8m6DqGDGlAn1hXpe2u6yYorLX0/6fhyWg1C/JR1sbaKPH/Xt+Fsx5ptMONX0uw=");
System.out.println(new String(encryptedMessageBytes));
Cipher decryptCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedMessageBytes = decryptCipher.doFinal(encryptedMessageBytes);
String decryptedMessage = new String(decryptedMessageBytes, StandardCharsets.UTF_8);
System.out.println(decryptedMessage);
}
}
This gives me following output
-----Private----------
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMv+t+D6/7ZY6m+CjD97NB989P2YjmGcE2yHUokyjmxVi/SxIu9MboiVNewR+mFjTFYPGgMWHz1/XeVGlinjN/5+0fdiO/JEvEUilFmkkIF3My11I09b9NZ9RJmpCNCbqOg7NSt6VD8IC/w19N25xwcofc3qbgfEjKSs0CgxfahrAgMBAAECgYEAiyLlEBKiryDeZchJGFNULdXw07dmBbWKmg+CgAl3kvSWTQM0rLsY+Rese6OXfy1XN6t9NnW0QSHKTUNj0JYl7btKEblVHERbjwavUe83tcNIc3o0xrGoBAzma14ZicPYm70JWixTO778lm5AXKl504+oOQyVYmfgXcevPXwdIkECQQDvO3DBuu6wp5nbwR4t0736HOH9jVIjJOS8oABUARDhNt1fkb8uEptDr5EomVRMqarJMAjSMpYxrUCpvgtf4nZ5AkEA2ksDr8pbbFvZPaAe0F43LmJtFM3PvCz87S93p20YjwVMmGV17sJ5t7a26HtubgRLEWq4z6rxq2oXPv4y1lstAwJAbj9cVUtKWIrEcutqdwAPmsXYt7p60ctcxjiOLihXmRJprnNCQX89olG0eZs/qBzAofrK9eNuJ/KJzC/SmhuJMQJAAz9gc6oQCCGprrgGHVV5frAqLUgOkh8dOC4fmpcN6XrLs+y2f3HXO7t1JypG704TC9RJoZVKeSFf7Sj8+qFqnwJBALRiQc9SG5Ht5TLo12W4l3bRaxpbo597BgKRjz3hqiySdqjZA9Qe84qmEKveZ9eWehbfqwzKmCbW43I1ZEFZ95o=
Encoding : PKCS#8
----------------------
-----Public----------
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDL/rfg+v+2WOpvgow/ezQffPT9mI5hnBNsh1KJMo5sVYv0sSLvTG6IlTXsEfphY0xWDxoDFh89f13lRpYp4zf+ftH3YjvyRLxFIpRZpJCBdzMtdSNPW/TWfUSZqQjQm6joOzUrelQ/CAv8NfTduccHKH3N6m4HxIykrNAoMX2oawIDAQAB
Encoding : X.509
----------------------
Test
�N::�`��\A���ƈ�~��5s���
�0�I�C�uƹx2�Z&Kں�"ьC�$
q��K���h�^<�5�E�Ɨ0B�͒Z�{��EDbDH�.��#:�e��h~j���������q�c��R�
Test
In the Nodejs side I am using the above public to encrypt my text.
index.js
const crypto = require("crypto");
var pubkey = "-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDL/rfg+v+2WOpvgow/ezQffPT9mI5hnBNsh1KJMo5sVYv0sSLvTG6IlTXsEfphY0xWDxoDFh89f13lRpYp4zf+ftH3YjvyRLxFIpRZpJCBdzMtdSNPW/TWfUSZqQjQm6joOzUrelQ/CAv8NfTduccHKH3N6m4HxIykrNAoMX2oawIDAQAB\n-----END PUBLIC KEY-----";
var plaintext = "Test"
var buffer = new Buffer.from(plaintext, "utf8");
var enc = crypto.publicEncrypt(pubkey, buffer);
var bs64 = enc.toString('base64');
console.log(enc.toString());
console.log(enc.toString('base64'));
this gives me following output
B��u���<⌂�lǚm0�W������1�%EN�7��‼��l��l�<�����k;�������GĦ9D8��Z��I�Oɺ♫��→P'�§�{k�Ɋ+-}?��rZ
woboAUytDXJLlKm7zbqNdxVORG+kio9kZxvMPOHruQfxwNEx7SVFTsw3oeETqbRs4NZskjzO2Nzjyms73vv758Dcy0fEpjlEOKmrWuG62knOT8m6DqGDGlAn1hXpe2u6yYorLX0/6fhyWg1C/JR1sbaKPH/Xt+Fsx5ptMONX0uw=
Now I tried using both the strings in java side for decryption.
When I try decoding the string, it gives me following error
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Data must not be longer than 128 bytes
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:346)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
at javax.crypto.Cipher.doFinal(Cipher.java:2168)
at com.mindtree.starr.wsr.RSAKeyPairGenerator.main(RSAKeyPairGenerator.java:90)
And, when I try decoding the base64 string, it gie me following error
Exception in thread "main" javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:379)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:290)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:365)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
at javax.crypto.Cipher.doFinal(Cipher.java:2168)
at com.mindtree.starr.wsr.RSAKeyPairGenerator.main(RSAKeyPairGenerator.java:90)
What am I doing wrong?
The problem was clearly described in the first comment and the solution is in second comment.
Correct transformation string for Cipher instance that worked for me is RSA/ECB/OAEPWithSHA-1AndMGF1Padding
So below instantiation for decryption Cipher works perfectly.
Cipher decryptCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
I have this issue where I dont know how to read my public key file, I have looked for a while now for solutions but they tend to not answer my question in my case. I have a program which generates a public and a private key, I have another method that writes them down in there own files respectively. This may sound silly but I really dont know how I can read the key from a file. This is needed as I want to do asymetrec encryption and so will be transphereing key files around. I will link my code below, any help is much appreaciated :)
If you need anymore detail to my explanation then feel free to ask.
Thanks!
Key Generation and storage methods:
public class Encryption {
public static PrivateKey privateKey;
public static PublicKey publicKey;
public void KeyGeneration() throws NoSuchAlgorithmException{
KeyPairGenerator Generator = KeyPairGenerator.getInstance("RSA"); // Creat the Generator object with RSA
Generator.initialize(1024); // Set the generator to make the 2048 bit key
KeyPair Pair = Generator.genKeyPair(); // Generate the key pair
publicKey = Pair.getPublic(); // Set the Public Key
privateKey = Pair.getPrivate(); // Set the private Key
System.out.println(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
System.out.println(Base64.getEncoder().encodeToString(privateKey.getEncoded()));
}
public void writeToFile(String filePath, byte[] key) throws IOException{
File fileToWriteto = new File(filePath);
fileToWriteto.getParentFile().mkdirs();
FileOutputStream FoutputStream = new FileOutputStream(fileToWriteto);
FoutputStream.write(key);
FoutputStream.flush();
FoutputStream.close();
}
}
The easiest way to save and load RSA key files is by using the encoded version. The below code is saving a private and a public key to a file in encoded form.
The simple output:
Save and load RSA Keys encoded
private key equals: true
public key equals: true
Warning: please note that the following code has no exception handling and is for educational purpose only.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
public class SaveLoadRsaKeysSo {
public static void main(String[] args) throws GeneralSecurityException, IOException {
System.out.println("Save and load RSA Keys encoded");
KeyPairGenerator rsaGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom random = new SecureRandom();
rsaGenerator.initialize(2048, random);
KeyPair rsaKeyPair = rsaGenerator.generateKeyPair();
PublicKey rsaPublicKey = rsaKeyPair.getPublic();
PrivateKey rsaPrivateKey = rsaKeyPair.getPrivate();
// save private & public key
Files.write(Paths.get("rsaPrivateKey.encoded"), rsaPrivateKey.getEncoded());
Files.write(Paths.get("rsaPublicKey.encoded"), rsaPublicKey.getEncoded());
// load private & public key
byte[] privateKeyBytesLoad = Files.readAllBytes(Paths.get("rsaPrivateKey.encoded"));
PrivateKey privateKeyLoad = getPrivateKeyFromEncoded(privateKeyBytesLoad);
byte[] publicKeyBytesLoad = Files.readAllBytes(Paths.get("rsaPublicKey.encoded"));
PublicKey publicKeyLoad = getPublicKeyFromEncoded(publicKeyBytesLoad);
System.out.println("private key equals: " + Arrays.equals(rsaPrivateKey.getEncoded(), privateKeyLoad.getEncoded()));
System.out.println("public key equals: " + Arrays.equals(rsaPublicKey.getEncoded(), publicKeyLoad.getEncoded()));
}
public static PrivateKey getPrivateKeyFromEncoded(byte[] key) throws GeneralSecurityException {
KeyFactory kf = KeyFactory.getInstance("RSA");
return (PrivateKey) kf.generatePrivate(new PKCS8EncodedKeySpec(key));
}
public static PublicKey getPublicKeyFromEncoded(byte[] key) throws GeneralSecurityException {
KeyFactory kf = KeyFactory.getInstance("RSA");
return (PublicKey) kf.generatePublic(new X509EncodedKeySpec(key));
}
}
I have code sample in Java and I need the same functionality in C#. Are there any alternatives to the classes, which are used for the sample?
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import javax.xml.bind.DatatypeConverter;
publicKey = publicKey.replaceAll("-----(BEGIN|END).*", "").trim();
X509EncodedKeySpec spec = new X509EncodedKeySpec(DatatypeConverter.parseBase64Binary(publicKey));
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PublicKey pKey = keyFactory.generatePublic(spec);
Signature ecdsaSign = Signature.getInstance("SHA256withECDSA");
ecdsaSign.initVerify(pKey);
ecdsaSign.update(stringToVerify.getBytes("UTF-8"));
if (ecdsaSign.verify(new BigInteger(ECDSA, 16).toByteArray())) {
// true
}
There's not anything in .NET (by itself) which can read the public key structure only. But if you can get the entirety of a certificate then you can write the following in .NET 4.6.1:
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace Demo
{
public static class DemoClass
{
public static bool ECDsaSha256Verify(string pemCert, string data, byte[] signature)
{
using (var cert = new X509Certificate2(Encoding.ASCII.GetBytes(pemCert)))
using (ECDsa ecdsa = cert.GetECDsaPublicKey())
{
if (ecdsa == null)
{
throw new ArgumentException("Certificate does not have an ECDSA key.");
}
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
return ecdsa.VerifyData(dataBytes, signature, HashAlgorithmName.SHA256);
}
}
}
}
I wasn't sure where your BigInteger signature value was coming from, so that I have just left as a byte array.
I am integrating with a .Net application which uses Symmetric encryption. My application is on Java. Following is the .Net code which was shared by the team which uses the Symmetric encryption;
public static string SymmetricEncrypt<T>(string value, string PrivateKey, string SALT_STRING) where T : SymmetricAlgorithm, new()
{
PasswordDeriveBytes rgb =
new PasswordDeriveBytes(PrivateKey ,
Encoding.Unicode.GetBytes(SALT_STRING));
SymmetricAlgorithm algorithm = new T();
byte[] rgbKey = rgb.GetBytes(algorithm.KeySize >> 3);
byte[] rgbIV = rgb.GetBytes(algorithm.BlockSize >> 3);
ICryptoTransform transform = algorithm.CreateEncryptor(rgbKey, rgbIV);
using (MemoryStream buffer = new MemoryStream())
{
using (CryptoStream stream =
new CryptoStream(buffer, transform, CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
{
writer.Write(value);
}
}
return Convert.ToBase64String(buffer.ToArray());
}
}
Looking at the .Net documentation, I could see that SymmetricEncrypt class by default uses Rijndael encryption. And also I have found a class similar to "PasswordDeriveBytes" implementation in bouncy castle which implements the "PKCS5S1" algorithm for key generation using the salt with an iteration count of 100. But still I am unable to generate the exact encryption to what is required by the .Net application. Following code is what i have tried so far;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import mtnsa.sorb.handler.PKCS5Test.PasswordDeriveBytes;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.generators.PKCS5S1ParametersGenerator;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Base64;
public class EncryptionHelper {
public static void main(String[] args)throws Exception {
encrypt("FTTH","HhN01vcEEtMmwdNFliM8QYg0Y89xzBOJJG7BHARC7g", "002400000480000094000000060200000024000052534131000400000100010085525e9438e9fae122f71ec7124" +
"443bf2f9f57f5f3760b3704df168493004b9ef68413f500d54fa9fa3869b42b1e2365204826e54b618d56e7e575f2" +
"7f675f0eae3ea8458a8ee1e92dc3f4bfc34fbe23851afa9d2c28fc8cd5b124f60a03a06bfb598bc3acbd8c4380ae" +
"f02cc58bdf955d140390f740a7e115c59e3b3b5758ca");
}
public static String encrypt(final String valueToEncrpt, final String saltString, final String privateKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{
String encrptedValue = null;
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] password = privateKey.getBytes();
byte[] salt = saltString.getBytes();
PKCS5S1ParametersGenerator generator = new PasswordDeriveBytes(new SHA1Digest());
generator.init(password, salt, 100);
byte[] keyArr = ((KeyParameter)generator.generateDerivedParameters(128)).getKey();
byte[] IvArr = ((KeyParameter)generator.generateDerivedParameters(128)).getKey();
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyArr,"AES"),new IvParameterSpec(IvArr));
byte[]test = cipher.doFinal(valueToEncrpt.getBytes());
System.out.println(new String(Base64.encode(test)));
return encrptedValue;
}
}
In the Java code i have given the sample SALT key and the PRIVATE key used for testing purposes. But still I am unable to get the exact value as generated by the .Net application. Following is an example plain text and the encrypted value which i got from the .Net application which i have failed to replicate in my Java code.
Plain text value : FTTH
Encrypted value : MjgmbdT3Vg6RW/7K1BjQ/Q==
Any help on this is much appreciated as i am currently out of ideas.
Thank you everyone for the valuable comments. I have requested the .Net module authors to change their implementation to use RFC2898DeriveBytes
I ran into a problem when trying to integrate with a payment processor (CCBill) who is requesting a string to be encrypted to be used as a token, using the TripleDES standard. My application is in Java, and the result I am getting back is not what the payment processor expects.
There is a post here that is addressing Perl<->PHP and Perl<->ColdFusion, but no solutions for Java.
The PERL version of the code looks like this:
#!/usr/bin/perl
# Perl Crypt Calamity (here be...something)
use strict;
use CGI;
use MIME::Base64;
use Crypt::TripleDES;
my $cgi = CGI->new();
my $param = $cgi->Vars();
$param->{key} = "bC5PEcLzvb+jY1FZWuP4pw50";
$param->{string} = "subscriptionId=0214288302000000207";
my $des = Crypt::TripleDES->new();
my $enc = $des->encrypt3($param->{string}, $param->{key});
$enc = encode_base64($enc);
$enc =~ s/\n//gs;
# resulting string (enc): yvT6h6jti9krth/BaA3cO3ABKult8N38fnEb24MS0BwnX+gc1NNgEA==
This is my little Java class trying to do the same as the perl script, but which returns a completely different value:
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.apache.commons.codec.binary.Base64;
public class Encoder {
public String encrypt(String message, String encryptionKey) throws Exception {
// handle the key
SecretKey secretKey = null;
byte[] keyValueAsBytes = Arrays.copyOf(encryptionKey.getBytes("UTF-8"), 24);
DESedeKeySpec keySpec = new DESedeKeySpec(keyValueAsBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
secretKey = keyFactory.generateSecret(keySpec);
// cipher
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
// encode
byte[] plainText = message.getBytes("UTF-8");
byte[] encryptedText = cipher.doFinal(plainText);
return Base64.encodeBase64String(encryptedText);
}
public static void main(String[] args) throws Exception{
String secretKey = "bC5PEcLzvb+jY1FZWuP4pw50";
String message = "subscriptionId=0214288302000000207";
Encoder enc = new Encoder();
System.out.println(enc.encrypt(message, secretKey));
//returns:hw6JzwdvmjwORzmitXcQ6vsmskK6vtdIObu+KYiGW4D4DRwNGHEX2w==
}
}
Any suggestions and help would be much appreciated.