Encrypting AES key with RSA public key - java

I'm writing a small application for transferring files, more or less as a way to learn more of the programmatic encryption underpinnings. The idea is to generate an RSA keypair, exchange public keys, and send the AES iv and key over for further decryption. I want to encrypt the AES key with the receivers RSA public key, like so:
// encode the SecretKeySpec
private byte[] EncryptSecretKey ()
{
Cipher cipher = null;
byte[] key = null;
try
{
cipher = Cipher.getInstance("RSA/ECB/NOPADDING");
// contact.getPublicKey returns a public key of type Key
cipher.init(Cipher.ENCRYPT_MODE, contact.getPublicKey() );
// skey is the SecretKey used to encrypt the AES data
key = cipher.doFinal(skey.getEncoded());
}
catch(Exception e )
{
System.out.println ( "exception encoding key: " + e.getMessage() );
e.printStackTrace();
}
return key;
}
I then write out the key value to the receiver, and decrypt it like so:
private SecretKey decryptAESKey(byte[] data )
{
SecretKey key = null;
PrivateKey privKey = null;
Cipher cipher = null;
System.out.println ( "Data as hex: " + utility.asHex(data) );
System.out.println ( "data length: " + data.length );
try
{
// assume this loads our private key
privKey = (PrivateKey)utility.loadLocalKey("private.key", false);
cipher = Cipher.getInstance("RSA/ECB/NOPADDING");
cipher.init(Cipher.DECRYPT_MODE, privKey );
key = new SecretKeySpec(cipher.doFinal(data), "AES");
System.out.println ( "Key decrypted, length is " + key.getEncoded().length );
System.out.println ( "data: " + utility.asHex(key.getEncoded()));
}
catch(Exception e)
{
System.out.println ( "exception decrypting the aes key: " + e.getMessage() );
e.printStackTrace();
return null;
}
return key;
}
In console, on the other side, I get this as output:
read_bytes for key: 16
data length: 16
Data as hex: <hex string>
Key decrypted, length is 256
java.security.InvalidKeyException: Invalid AES key length: 256 bytes
Furthermore, if I create a byte array of size 16 and put the cipher.doFinal(data) output into it, the array is seemingly resized to 256 bytes (.length says so, at least). Why would this be, and further, what am I doing incorrectly?
edit
I solved this, and thought I'd post the issue in case someone runs into this. The problem, it turns out, was the RSA/ECB/NOPADDING. For some odd reason it was screwing up my creation of the SecretKey when I transferred it over to the client. It might have something to do with how I'm generating keypairs (i'm using getInstance("RSA") for that), but I'm not entirely sure.

As owlstead mentioned, you cannot just use "raw" RSA without padding for encryption/decryption. For one it is very insecure, and for another, the Java libraries do not even support it. Below is the working code for the encryption/decryption of the AES key using RSA keypairs.
private byte[] EncryptSecretKey ()
{
Cipher cipher = null;
byte[] key = null;
try
{
// initialize the cipher with the user's public key
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, contact.getPublicKey() );
key = cipher.doFinal(skey.getEncoded());
}
catch(Exception e )
{
System.out.println ( "exception encoding key: " + e.getMessage() );
e.printStackTrace();
}
return key;
}
Decryption of the AES key looks like this:
private SecretKey decryptAESKey(byte[] data )
{
SecretKey key = null;
PrivateKey privKey = null;
Cipher cipher = null;
try
{
// this is OUR private key
privKey = (PrivateKey)utility.loadLocalKey(
ConfigFrame.privateKeyLocation, false);
// initialize the cipher...
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privKey );
// generate the aes key!
key = new SecretKeySpec ( cipher.doFinal(data), "AES" );
}
catch(Exception e)
{
System.out.println ( "exception decrypting the aes key: "
+ e.getMessage() );
return null;
}
return key;
}

You cannot just use "raw" RSA to encrypt data without any padding. You need some kind of padding scheme, if only for security reasons. Normally "RSA/ECB/PKCS1Padding" is used. This can encrypt data up to 11 bytes less than the key size. It makes sure that the data fits in the modulus, and adds at least 8 bytes of random data to make sure that encrypting e.g. the word "Yes" twice does not result in two identical cipher texts. Finally, it makes sure you can find out the size in octets of the encrypted data, so you can simply encrypt the 16, 24 or 32 bytes that make up the AES key.

One thing to remember is that with RSA and actually many other
algorithms including AES usually, the "useful" data that you supply
isn't literally the data that's encrypted. Usually, some extra data
needs to be included, for example, indicating the actual length of the
data in some way, data for any integrity checking... To the user, the
number of input bytes doesn't necessarily equal the number of bytes
following encryption.
Comment Source
To get the right key size you can use an HashAlgorithm on the key (SHA), which will give you a fixed output-size. Otherwise you can just use the first 16bytes as key and ignore the rest? Good luck.

Related

Openssl (shell script) equivalent of java decryption code

Need help with openssl, What would be the openssl equivalent of the below java method?
private static String decryptString(String value, String myKey) {
MessageDigest sha = null;
SecretKeySpec secretKey = null;
try {
byte[] key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return (new String(cipher.doFinal(Base64.decodeBase64(value))));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
The function is digesting a string (myKey) using SHA-1 and then using the first 16 bytes of the resulting digest as the key for an AES128-ECB decryption operation. Before decryption, the ciphertext is first base64 decoded.
To digest a string using SHA-1 use the code here:
https://wiki.openssl.org/index.php/EVP_Message_Digests
That code actually uses SHA-256. To make it do SHA-1 instead replace the instance of EVP_sha256() with EVP_sha1(). The first 16 bytes of the result is your "key".
Next the input "value" is base64 decoded. There is some sample code to do that with OpenSSL here:
http://www.ioncannon.net/programming/122/howto-base64-decode-with-cc-and-openssl/
Finally, to do the AES-ECB decryption operation use the code here:
https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption#Decrypting_the_Message
That code is using AES256-CBC. To make it do AES128-ECB instead replace the instance of EVP_aes_256_cbc() with EVP_aes_128_ecb(). The key argument is as you calculated above. The iv argument is just NULL for ECB. The ciphertext is the base64 decoded data that you calculated above. Note that the "PKCS5PADDING" part of the Java code is the default in OpenSSL anyway, so nothing special needs to be done for that.
The plaintext that has been output from the decryption operation is the return value from your Java function.

How to properly recreate SecretKey from string

I'm trying to make an encryption-decryption app. I've got two classes - one with functions to generate the key, encrypt and decrypt, second one for JavaFX GUI. In the GUI class I've got 4 textareas: 1st to write text to encrypt, 2nd for encrypted text, 3rd for the key (String encodedKey = Base64.getEncoder().encodeToString(klucz.getEncoded());) and 4th for decrypted text.
The problem is, I am not able to decrypt the text. I'm trying to recreate the SecretKey like this:
String encodedKey = textAreaKey.getText();
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
SecretKey klucz = new SecretKeySpec(decodedKey, "DESede");
When I encrypt the key looks like this: com.sun.crypto.provider.DESedeKey#4f964d80 and when I try to recreate it: javax.crypto.spec.SecretKeySpec#4f964d80 and I'm getting javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
Here is my 1st class:
public class Encryption {
public static SecretKey generateKey() throws NoSuchAlgorithmException {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
KeyGenerator keygen = KeyGenerator.getInstance("DESede");
keygen.init(168);
SecretKey klucz = keygen.generateKey();
return klucz;
}
static byte[] encrypt(byte[] plainTextByte, SecretKey klucz)
throws Exception {
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, klucz);
byte[] encryptedBytes = cipher.doFinal(plainTextByte);
return encryptedBytes;
}
static byte[] decrypt(byte[] encryptedBytes, SecretKey klucz)
throws Exception {
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, klucz);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return decryptedBytes;
}
}
edit
btnEncrypt.setOnAction((ActionEvent event) -> {
try {
String plainText = textAreaToEncrypt.getText();
SecretKey klucz = Encryption.generateKey();
byte[] plainTextByte = plainText.getBytes();
byte[] encryptedBytes = Encryption.encrypt(plainTextByte, klucz);
String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
textAreaEncryptedText.setText(encryptedText);
byte[] byteKey = klucz.getEncoded();
String stringKey = Base64.getEncoder().encodeToString(byteKey);
textAreaKey.setTextstringKey
} catch (Exception ex) {
ex.printStackTrace();
}
});
btnDecrypt.setOnAction((ActionEvent event) -> {
try {
String stringKey = textAreaKey.getText();
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
SecretKey klucz2 = new SecretKeySpec(decodedKey, "DESede");
String encryptedText = textAreaEncryptedText.getText();
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText.getBytes());
byte[] decryptedBytes = Encryption.decrypt(encryptedBytes, klucz2;
String decryptedText = Base64.getEncoder().encodeToString(decryptedBytes);
textAreaDecryptedText.setText(decryptedText);
} catch (Exception ex) {
ex.printStackTrace();
}
});
One of your problems is here:
String encryptedText = new String(encryptedBytes, "UTF8");
Generally, many byte sequences in cipher text are not valid UTF-8–encoded characters. When you try to create a String, this malformed sequences will be replaced with the "replacement character", and then information from the the cipher text is irretrievably lost. When you convert the String back to bytes and try to decrypt it, the corrupt cipher text raises an error.
If you need to represent the cipher text as a character string, use base-64 encoding, just as you do for the key.
The other principal problem is that you are aren't specifying the full transformation. You should specify the "mode" and "padding" of the cipher explicitly, like "DESede/ECB/PKCS5Padding".
The correct mode will depend on your assignment. ECB is generally not secure, but more secure modes add a bit of complexity that may be outside the scope of your assignment. Study your instructions and clarify the requirements with your teacher if necessary.
There are two main issues:
You should not use user entered password as a key (there are difference between them). The key must have specific size depending on the cipher (16 or 24 bytes for 3des)
Direct 3DES (DESede) is a block cipher encrypting 8 bytes at once. To encrypt multiple blocks, there are some methods defined how to do that properly. It is calls Block cipher mode.
For proper encryption you need to take care of a few more things
Creating a key from the password
Let's assume you want to use DESede (3des). The key must have fixed size - 16 or 24 bytes. To properly generate a key from password you should use PBKDF. Some people are sensitive to "must use", however neglecting this step really compromises the encryption security mainly using user-entered passwords.
For 3DES you can use :
int keySize = 16*8;
int iterations = 800000;
char[] password = "password".toCharArray();
SecureRandom random = new SecureRandom();
byte[] salt = random.generateSeed(8);
SecretKeyFactory secKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
KeySpec spec = new PBEKeySpec(password, salt, iterations, keySize);
SecretKey pbeSecretKey = secKeyFactory.generateSecret(spec);
SecretKey desSecret = new SecretKeySpec(pbeSecretKey.getEncoded(), "DESede");
// iv needs to have block size
// we will use the salt for simplification
IvParameterSpec ivParam = new IvParameterSpec(salt);
Cipher cipher = Cipher.getInstance("DESEde/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, desSecret, ivParam);
System.out.println("salt: "+Base64.getEncoder().encodeToString(salt));
System.out.println(cipher.getIV().length+" iv: "+Base64.getEncoder().encodeToString(cipher.getIV()));
byte[] ciphertext = cipher.doFinal("plaintext input".getBytes());
System.out.println("encrypted: "+Base64.getEncoder().encodeToString(ciphertext));
if you can ensure that your password has good entropy (is long and random enough) you may be good with a simple hash
MessageDigest dgst = MessageDigest.getInstance("sha-1");
byte[] hash = dgst.digest("some long, complex and random password".getBytes());
byte[] keyBytes = new byte[keySize/8];
System.arraycopy(hash, 0, keyBytes, 0, keySize/8);
SecretKey desSecret = new SecretKeySpec(keyBytes, "DESede");
The salt serves to randomize the output and should be used.
The output of the encryption should be salt | cipthertext | tag (not necessarily in this order, but you will need all of these for proper encryption).
To decrypt the output, you will need to split the output to salt, ciphertext and the tag.
I see zero vectors ( static salt or iv ) very often in examples from StackOverflow, but in many cases it may lead to broken ciphers revelaling key or plaintext.
The initialization vector iv is needed for block chain modes (encrypting longer input than a single block), we could use the salt from the key as well
when having the same size ( 8 bytes in our case). For really secure solution the password salt should be longer.
The tag is an authentication tag, to ensure that nobody has manipulated with the ciphertext. You could use HMAC of the plaintext or ciphertext. It is important you should use different key for HMAC than for encryption. However - I believe in your case your homework will be ok even without the hmac tag

Java: Encrypting and Decrypting using DES

I'm trying to create a simple encryption/decryption program, but i'm having problems when decrypting. The way the program works, I get string input from the user, then encrypt using DES, convert to Base64 and give the user the converted secret key. However, when I get the secret key from the user and I try to decrypt, I get either error:
java.security.InvalidKeyException: No installed provider supports this key: (null)
or
javax.crypto.BadPaddingException
I don't know if the fault is at the time of encryption or if it's the decryption. Here's the respective snippets of code:
import javax.xml.bind.DatatypeConverter;
public static boolean encrypt(byte[] text){
Boolean yorn = false;
try{
myDesKey = KeyGenerator.getInstance("DES").generateKey();
//myDeskKey = myDesKey.toString();
Cipher desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
//I felt it would be better seeing the secret key as "woatDnBJLAg=" instead of "com.sun.crypto.provider.DESKey#18765"
if (myDesKey != null) {
stringKey = DatatypeConverter.printBase64Binary(myDesKey.getEncoded());
System.out.println("actual secret_key:" + myDesKey);
byte[] encodedKey = DatatypeConverter.parseBase64Binary(stringKey);
myDesKey = new SecretKeySpec(encodedKey, 0, encodedKey.length,
"DES");
System.out.println("after encode & decode secret_key:"
+ DatatypeConverter.printBase64Binary(myDesKey.getEncoded()));
}
textEncrypted = desCipher.doFinal(text);
yorn = true;
JTextArea textArea = new JTextArea(2,50);
textArea.setText("Your encryption key is: " + stringKey + " . Ensure you store it in a safe place" );// + DatatypeConverter.printBase64Binary(myDesKey.getEncoded()));
textArea.setEditable(false);
JOptionPane.showMessageDialog(null, new JScrollPane(textArea), "RESULT", JOptionPane.INFORMATION_MESSAGE);
}catch(Exception e)
{
System.out.println("There has been an error encrypting the file");
yorn = false;
}
return yorn;
Decryption
public static String decrypt(byte[] cipherText, SecretKey key,String key1)
{
String plainText = "";
try{
SecretKey myDesKey = key;
if(key == null){
JOptionPane.showMessageDialog(null, "We were unable to find your decryption key. Please enter your decryption key below: ");
JTextArea textBox = new JTextArea(1,15);
JOptionPane.showMessageDialog(null, new JScrollPane(textBox),"Enter your decryption key ",JOptionPane.PLAIN_MESSAGE);
//myDesKey = textBox.toSecretKey;
}
Cipher desCipher;
desCipher = Cipher.getInstance("DES");
desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] textDecrypted = desCipher.doFinal(cipherText);
plainText = new String(textDecrypted);
JOptionPane.showMessageDialog(null, plainText, "DECRYPTED MESSAGE", 0);
}catch(Exception e)
{
System.out.println("There has been an error decrypting the file");
System.out.println(e);
}return plainText;
}
}
I know that I'm probably getting the errors because i've combined so many jumbled bits of code from all over stack and I seem to have lost the plot, but any help will be greatly appreciated.
Thanks!!
You're using two different ciphers. Cipher.getInstance("DES") is not fully specified, so it probably defaults to Cipher.getInstance("DES/ECB/PKCS5Padding") which is different from the CBC mode you're using during encryption.
Secondly, since you're using CBC mode, you need to manage the initialization vector (IV), but you don't do this at all. You can either provide the IV as a third parameter for Cipher#init or let it automatically be generated as you currently do, but then you have to send the IV (desCipher.getIV()) along with the ciphertext to the receiver. The IV doesn't have to be secret. A common way is to prepend it to the ciphertext and slice it off before decryption.
Lastly, the key you're using during decryption is not the same key that you've used during encryption, because you've re-encoded the key after encryption, but didn't decode it back.

3des with 2 different keys in java getting null

3des with 2 different keys in java getting null.
import java.security.spec.*;
import javax.crypto.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class DESedeEncryption {
public static void main(String[] args) {
SecretKey k1 = generateDESkey();
SecretKey k2 = generateDESkey();
String firstEncryption = desEncryption("plaintext", k1);
System.out.println("firstEncryption Value : "+firstEncryption);
String decryption = desDecryption(firstEncryption, k2);
System.out.println("decryption Value : "+decryption);
String secondEncryption = desEncryption(decryption, k1);
System.out.println("secondEncryption Value : "+secondEncryption);
}
public static SecretKey generateDESkey() {
KeyGenerator keyGen = null;
try {
keyGen = KeyGenerator.getInstance("DESede");
} catch (Exception ex) {
}
keyGen.init(112); // key length 56
SecretKey secretKey = keyGen.generateKey();
return secretKey;
}
public static String desEncryption(String strToEncrypt, SecretKey desKey) {
try {
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, desKey);
BASE64Encoder base64encoder = new BASE64Encoder();
byte[] encryptedText = cipher.doFinal(strToEncrypt.getBytes());
String encryptedString =base64encoder.encode(encryptedText);
return encryptedString;
} catch (Exception ex) {
}
return null;
}
public static String desDecryption(String strToDecrypt, SecretKey desKey) {
try {
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, desKey);
BASE64Decoder base64decoder = new BASE64Decoder();
byte[] encryptedText = base64decoder.decodeBuffer(strToDecrypt);
byte[] plainText = cipher.doFinal(encryptedText);
String decryptedString= bytes2String(plainText);
return decryptedString;
} catch (Exception ex) {
}
return null;
}
private static String bytes2String(byte[] bytes) {
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i <bytes.length; i++) {
stringBuffer.append((char) bytes[i]);
}
return stringBuffer.toString();
}
}
while i'm running the above code i'm getting null values. plz help.
output:
firstEncryption Value : jAihaGgiOzBSFwBWo3gpbw==
decryption Value : null
secondEncryption Value : null
getting error:
firstEncryption Value : ygGPwCllarWvSH8td55j/w==
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DESedeCipher.java:
294)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at DESedeEncryption.desDecryption(DESedeEncryption.java:145)
at DESedeEncryption.main(DESedeEncryption.java:107)
decryption Value : null
java.lang.NullPointerException
at DESedeEncryption.desEncryption(DESedeEncryption.java:130)
at DESedeEncryption.main(DESedeEncryption.java:109)
secondEncryption Value : null
Symmetric ciphers work by encrypting and decrypting with the same key, hence the name symmetric. (And for most modes also the same IV, but the IV doesn't need to be secret.) You're encrypting with one key and decrypting with an independent key which is different with overwhelming probability (i.e. it might the same once a zillion quillion eternities). That won't work.
Perhaps you are confused by the description of Triple-DES also known as 3DES DESede or TDEA. The original DES (or DEA) cipher uses a 56-bit key (in 8 bytes) which was secure in the 1960s but not now. Triple-DES was defined using DES as a building block but with a bundle of 3 keys (k1,k2,k3) which can also be treated as a combined 168-bit key (in 24 bytes); if k3=k1 the key is described as 112-bits although it is still stored as 24 bytes. Your call to KeyGenerator "DESede" .init(112) does exactly that; it generates a 24-byte bundle with k3=k1 and k2 different. For convenience in the past Triple-DES is defined to use single-DES to encrypt with k1, decrypt with k2, and encrypt with k3, and the reverse when decrypting, hence the name DES-EDE or DESede. See http://en.wikipedia.org/wiki/Triple_DES .
If you really want, you can implement Triple-DES yourself in Java using Cipher "DES" by doing E,D,E (or reverse D,E,D if used) and then wrapping the mode around that, see Java Triple DES encryption with 2 different keys . But it's much easier to just use Cipher "DESede", which it does the lot for you, treating DESede like any other symmetric cipher primitive, as answered in that question.
Also, mode ECB is dangerous. It is an exaggeration to say it is always insecure as some people do, but historically very many applications using it designed by non-experts are insecure. Unless you know much more than is evident in your question, or are following (or interfacing to) a design by someone who does, use a better established mode like CBC or CTR.

Leading to same value on Decryption with DESede CBC NoPadding

I am asked to verify if the encryption is working ok. I am given input hex text of 238 bytes. Asked to use DESede/CBC/NoPadding algorithm. I am also given encrypted value. Of course, I am given key also ( Given two bytes. Added third byte as copy of first byte to make it three bytes)
(238 bytes+ 2 bytes padding)
Problem is: Encrypted value from my code does not match completely with the given encrypted value ( only First 56 bytes are matching).
What I did is: Decrypted the given encrypted value and encrypted value produced from my code. Both of these decrypted values are matching with the given input.
That means, I have two encrypted values for which the decrypted value is the same.
Using InitialVector of Zeros.(8 zero bytes).
Can somebody throw some light? I am sure I am missing something. Thanks for any help.
Using javax.crypto.Cipher.getInstance for getting Cipher instance. Using SecretKeyFactory and DESedeKeySpec classes to generate key
Edited:
public String encrypt(byte[] sourceDataInBytes, String keyInHex, String cryptoMode, String cryptoPadding)
{
Cipher des3cipher = null;
IvParameterSpec ivParamSpec = null;
String transformation = "DESede"+"/"+ cryptoMode+"/"+cryptoPadding;
byte[] encryptedDataInBytes = null;
try{
des3cipher = Cipher.getInstance(transformation);
Key key = generate3DESKey(keyInHex);
if(cryptoMode.equalsIgnoreCase("CBC"))
{
ivParamSpec = new IvParameterSpec(INITIAL_VECTOR_SALT);
des3cipher.init(CYPHER_ENCRYPT_MODE, key, (AlgorithmParameterSpec)ivParamSpec );
}else{
des3cipher.init(CYPHER_ENCRYPT_MODE, key);
}
if(cryptoPadding.equals("NoPadding")){'
sourceDataInBytes = addPadding(sourceDataInBytes, 8);
}
encryptedDataInBytes = des3cipher.doFinal(sourceDataInBytes);
}catch(Exception e){
e.printStackTrace();
}
return encryptedDataInBytes ;
}
public Key generate3DESKey(String srcInHex)
{
Key key = null;
if(src != null)
{
byte[] bk = null;
try{
bk = hexStringToByte(src + src.length==32 ? src.substring(0,16) : ""));
DESedeKeySpec des3KeySpec = new DESedeKeySpec(bk);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
key = keyFactory.generateSecret(des3KeySpec);
}catch(Exception e){
e,printStyackTrace();
}
}
return key;
}

Categories