Java Cipher says invalid key length - java

Hey guys after trying out stuff for about an hour I am stuck. I just wanted to try out encryption in java and got stumped with many error messages I just don't understand. After looking up in the javadocs how long the key needs to be for AES, it says 56, I naturally thought it means I have to have 56 bits, so a 7 long byte array. But it doesn't seem to work. Here is the stack trace:
java.security.InvalidKeyException: Invalid key length: 7 bytes null
at com.sun.crypto.provider.DESCipher.engineGetKeySize(DESCipher.java:373)
at javax.crypto.Cipher.passCryptoPermCheck(Cipher.java:1067)
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1038)
at javax.crypto.Cipher.implInit(Cipher.java:805)
at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
at javax.crypto.Cipher.init(Cipher.java:1396)
at javax.crypto.Cipher.init(Cipher.java:1327)
at com.skrelpoid.secure.Crypt.encrypt(Crypt.java:34)
at com.skrelpoid.secure.Crypt.main(Crypt.java:95)
Exception in thread "main" java.lang.NullPointerException
at com.skrelpoid.secure.Crypt.decrypt(Crypt.java:47)
at com.skrelpoid.secure.Crypt.main(Crypt.java:97)`
And here is my code:
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
// adapted from http://stackoverflow.com/a/1205272/
public class Crypt {
private static byte[] ivBytes;
private static Cipher cipher;
private static SecretKeySpec keySpec;
private static IvParameterSpec ivSpec;
private static Random random;
private static long seed;
private Crypt() {
}
private static byte[] ivBytes() {
random.setSeed(seed);
byte[] bytes = new byte[7];
random.nextBytes(bytes);
return bytes;
}
public static String encrypt(String key, String input) {
prepare(key);
byte[] inputBytes = input.getBytes();
try {
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = new byte[cipher.getOutputSize(inputBytes.length)];
int enc_len = cipher.update(inputBytes, 0, inputBytes.length, encrypted, 0);
enc_len += cipher.doFinal(encrypted, enc_len);
return new String(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static String decrypt(String key, String input) {
prepare(key);
byte[] inputBytes = input.getBytes();
try {
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decrypted = new byte[cipher.getOutputSize(inputBytes.length)];
int dec_len = cipher.update(inputBytes, 0, inputBytes.length, decrypted, 0);
dec_len += cipher.doFinal(decrypted, dec_len);
return new String(decrypted);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private static void prepare(String key) {
byte[] keyBytes = new byte[7];
byte[] bytesFromKey = key.getBytes();
int length = keyBytes.length < bytesFromKey.length ? keyBytes.length : bytesFromKey.length;
System.arraycopy(bytesFromKey, 0, keyBytes, 0, length);
// if the length is smaller then keyBytes length, there are trailing
// zeros in the keyBytes. Fill them with the use of the seed;
if (length < keyBytes.length) {
random.setSeed(seed);
byte[] newBytes = new byte[keyBytes.length - length];
random.nextBytes(newBytes);
System.arraycopy(newBytes, 0, keyBytes, length, newBytes.length);
}
keySpec = new SecretKeySpec(keyBytes, "DES");
ivSpec = new IvParameterSpec(ivBytes);
try {
cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
public static void init(String id) {
seed = id.hashCode();
random = new Random(seed);
ivBytes = ivBytes();
}
public static final void main(String[] args) {
init("123456");
String str = "ILikeTurtles";
String key = "KEY123";
String encrypted = encrypt(key, str);
System.out.println(encrypted);
System.out.println(decrypt(key, encrypted));
}
}
I would really appreciate if someone could help me get that code to work.
Thanks in advance

DES requires 8 byte keys and an 8 byte IV.

Related

Cipher Algorithm AES CBC Insecure Android

I am currently using Cipher cipher = Cipher.getInstance ("AES / CBC / PKCS5Padding") on my Android app.
Those responsible for the security of the app tell me this: "It should also be noted that AES encryption is secure when it is not AES CBC.", so they want me to modify the algorithm.
I tried AES/GCM/NoPadding and AES/CTR/PKCS5Padding, if I uninstall the old version and install it again, the app works, but if I install it on top of a version with CBC I get the following error: javax.crypto.BadPaddingException: pad block corrupted
How can I solve this? I am afraid that if I update the app that is in the store, this error will happen to end users.
Notes:
public static String encrypt (String plaintext, String pwd) {
try {
byte [] salt = generateSalt ();
SecretKey key = deriveKey (salt, pwd);
Cipher cipher = Cipher.getInstance (CIPHER_ALGORITHM);
byte [] iv = generateIv (cipher.getBlockSize ());
IvParameterSpec ivParams = new IvParameterSpec (iv);
cipher.init (Cipher.ENCRYPT_MODE, key, ivParams);
byte [] cipherText = cipher.doFinal (plaintext.getBytes ("UTF-8"));
if (salt! = null) {
return String.format ("% s% s% s% s% s", toBase64 (salt), DELIMITER,
toBase64 (iv), DELIMITER, toBase64 (cipherText));
}
return String.format ("% s% s% s", toBase64 (iv), DELIMITER,
toBase64 (cipherText));
} catch (GeneralSecurityException e) {
throw new RuntimeException (e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException (e);
}
}
public static String decrypt (byte [] cipherBytes, SecretKey key, byte [] iv) {
try {
Cipher cipher = Cipher.getInstance (CIPHER_ALGORITHM);
IvParameterSpec ivParams = new IvParameterSpec (iv);
cipher.init (Cipher.DECRYPT_MODE, key, ivParams);
byte [] plaintext = cipher.doFinal (cipherBytes);
String plainrStr = new String (plaintext, "UTF-8");
return plainrStr;
} catch (GeneralSecurityException e) {
throw new RuntimeException (e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException (e);
}
}
etc...
Update!
I decided to make the code cleaner and here it is for you to understand. My goal was to replace "AES / CBC / PKCS7Padding" with "AES / GCM / NoPadding", as they consider AES with CBC unsafe :(
Questions that arose for this GCM implementation: do I have to use GCMParameterSpec on the cipher? Do I need to import the BouncyCastle provider?
public static final String PBKDF2_DERIVATION_ALGORITHM = "PBKDF2WithHmacSHA1";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";
//private static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding";
private static String DELIMITER = "]";
private static final int PKCS5_SALT_LENGTH = 8;
private static SecureRandom random = new SecureRandom();
private static final int ITERATION_COUNT = 1000;
private static final int KEY_LENGTH = 256;
public static String encrypt(String plaintext, String pwd) {
byte[] salt = generateSalt();
SecretKey key = deriveKey(pwd, salt);
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] iv = generateIv(cipher.getBlockSize());
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
byte[] cipherText = cipher.doFinal(plaintext.getBytes("UTF-8"));
return String.format("%s%s%s%s%s", toBase64(salt), DELIMITER, toBase64(iv), DELIMITER, toBase64(cipherText));
} catch (GeneralSecurityException | UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static String decrypt(String ciphertext, String pwd) {
String[] fields = ciphertext.split(DELIMITER);
if (fields.length != 3) {
throw new IllegalArgumentException("Invalid encypted text format");
}
byte[] salt = fromBase64(fields[0]);
byte[] iv = fromBase64(fields[1]);
byte[] cipherBytes = fromBase64(fields[2]);
SecretKey key = deriveKey(pwd, salt);
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, ivParams);
byte[] plaintext = cipher.doFinal(cipherBytes);
return new String(plaintext, "UTF-8");
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private static byte[] generateSalt() {
byte[] b = new byte[PKCS5_SALT_LENGTH];
random.nextBytes(b);
return b;
}
private static byte[] generateIv(int length) {
byte[] b = new byte[length];
random.nextBytes(b);
return b;
}
private static SecretKey deriveKey(String pwd, byte[] salt) {
try {
KeySpec keySpec = new PBEKeySpec(pwd.toCharArray(), salt, ITERATION_COUNT, KEY_LENGTH);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBKDF2_DERIVATION_ALGORITHM);
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
return new SecretKeySpec(keyBytes, "AES");
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
private static String toBase64(byte[] bytes) {
return Base64.encodeToString(bytes, Base64.NO_WRAP);
}
public static byte[] fromBase64(String base64) {
return Base64.decode(base64, Base64.NO_WRAP);
}

AES 256 Text Encryption returning different values

I'm trying to replicate an encryption method based on another C# method that I found.
The C# Encryption method EncryptText(word, password) call to another method AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) to encrypt plain text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var f = EncryptText("763059", "515t3ma5m15B4d35");//(word, password)
Console.WriteLine(f);
}
public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
public static string EncryptText(string input, string password)
{
byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
string result = Convert.ToBase64String(bytesEncrypted);
return result;
}
}
}
Using word 763059 and password 515t3ma5m15B4d35, the output is the following:
3cHrXxxL1Djv0K2xW4HuCg==
UPDATE:
Now, I created a Java Class main where I'm trying to replicate previous code:
public class main {
final static String PASSWORD = "515t3ma5m15B4d35";
final static byte[] SALT = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};
final static int KEY_SIZE = 256;
final static int BLOCK_SIZE = 128;
final static int ITERATIONS = 1000;
public static void main(String[] args) {
System.out.println(encryptText("763059", PASSWORD));
}
public static String encryptText(String word, String password) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes("UTF-8"));
password = new String(md.digest(), "UTF-8");
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password.toCharArray(), SALT, ITERATIONS, KEY_SIZE);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec skey = new SecretKeySpec(tmp.getEncoded(), "AES");
byte[] iv = new byte[BLOCK_SIZE / 8];
IvParameterSpec ivspec = new IvParameterSpec(iv);
Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
ci.init(Cipher.ENCRYPT_MODE, skey, ivspec);
byte[] result = ci.doFinal(word.getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(result);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | InvalidKeySpecException ex) {
return null;
}
}
}
UPDATE:
I read about using 256 bits keys in Java, and I found that I need to add Java Cryptography Extensions to allow 256 keys (Because I'm working with JDK7).
Then I added the libreries to the project, also I change the line:
KeySpec spec = new PBEKeySpec(password.toCharArray(), SALT, ITERATIONS, KEY_SIZE);
With the Key Value:
final static int KEY_SIZE = 256;
Now the output is the following:
J1xbKOjIeXbQ9njH+67RNw==
I still can't achieve my goal. Any Suggestion?
Finally I decided to use the BouncyCastle API to use the functionality of RijndaelEngine, as well as to generate the 256-bit key with PKCS5S2ParametersGenerator.
I created the RijndaelEncryption class to be able to perform the encryption as in the C# code:
public class RijndaelEncryption {
public String encryptString(String word, String password, byte[] salt, int iterations, int keySize, int blockSize) {
try {
byte[] pswd = sha256String(password, "UTF-8");
PKCS5S2ParametersGenerator key = keyGeneration(pswd, salt, iterations);
ParametersWithIV iv = generateIV(key, keySize, blockSize);
BufferedBlockCipher cipher = getCipher(true, iv);
byte[] inputText = word.getBytes("UTF-8");
byte[] newData = new byte[cipher.getOutputSize(inputText.length)];
int l = cipher.processBytes(inputText, 0, inputText.length, newData, 0);
cipher.doFinal(newData, l);
return new String(Base64.encode(newData), "UTF-8");
} catch (UnsupportedEncodingException | IllegalStateException | DataLengthException | InvalidCipherTextException e) {
return null;
}
}
public BufferedBlockCipher getCipher(boolean encrypt, ParametersWithIV iv) {
RijndaelEngine rijndael = new RijndaelEngine();
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(rijndael));
cipher.init(encrypt, iv);
return cipher;
}
public ParametersWithIV generateIV(PKCS5S2ParametersGenerator key, int keySize, int blockSize) {
try {
ParametersWithIV iv = null;
iv = ((ParametersWithIV) key.generateDerivedParameters(keySize, blockSize));
return iv;
} catch (Exception e) {
return null;
}
}
public PKCS5S2ParametersGenerator keyGeneration(byte[] password, byte[] salt, int iterations) {
try {
PKCS5S2ParametersGenerator key = new PKCS5S2ParametersGenerator();
key.init(password, salt, iterations);
return key;
} catch (Exception e) {
return null;
}
}
public byte[] sha256String(String password, Charset charset) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes(charset));
return md.digest();
} catch (NoSuchAlgorithmException ex) {
return null;
}
}
public byte[] sha256String(String password, String charset) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes(charset));
return md.digest();
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
return null;
}
}
}
And I tested in main method:
public static void main(String[] args) {
RijndaelEncryption s = new RijndaelEncryption();
byte[] salt = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};
String encryptStr = s.encryptString("763059", "515t3ma5m15B4d35", salt, 1000, 256, 128);
System.out.println("Encryptation: " + encryptStr);
}
To get:
Encryptation: 3cHrXxxL1Djv0K2xW4HuCg==
I am not any C# expert, but there are a few things to be checked:
Reading the documentation about Rfc2898DeriveBytes I see the function is using SHA1 hash, so try you may try to use PBKDF2WithHmacSHA1
On both instances (Rfc2898DeriveBytes, PBEKeySpec) you should make sure you the key size is the same (256 bit), it is surely wrong in your Java code
You may try to encode and print the keys to really make sure they are the same.
I need to add Java Cryptography Extensions to allow 256 keys.
Depends on your JVM version. I believe Oracle JDK since v. 1.8u162 by default contains the Unlimited Strength JCE policy. If you take any current JRE version, you should be ok
Additional: you are using (static) zero array IV, which is not secure
I have an answer for the original question. For future reference without bouncycastle.
You had a few problems.
Key size needed to be 256 + 128 (blocksize as well)
C# and Java byte[] don't act the same because java bytes are always signed which messes with the encryption of the password.
Both of these pieces of code give as output:
xD4R/yvV2tHajUS9p4kqJg==
C# code:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace tryencryption
{
class Program
{
static void Main(string[] args)
{
var f = EncryptText("yme", "515t3ma5m15B4d35");//(word, password)
Console.WriteLine(f);
Console.ReadKey();
}
public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, string passwordString)
{
byte[] encryptedBytes = null;
byte[] salt = new byte[] { (byte)0x49, (byte)0x64, (byte)0x76, (byte)0x65, (byte)0x64, (byte)0x65, (byte)0x76, (byte)0x61, (byte)0x6e, (byte)0x20, (byte)0x4d, (byte)0x65, (byte)0x76 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordString, salt, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
public static string EncryptText(string input, string password)
{
byte[] bytesToBeEncrypted = Encoding.Unicode.GetBytes(input);
byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, password);
string result = Convert.ToBase64String(bytesEncrypted);
return result;
}
}
}
Java code (this was from an android project bcs that's my usecase but should work everywhere):
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String result = encrypt("yme", "515t3ma5m15B4d35");
}
private static String encrypt(String word, String password) {
byte[] salt = new byte[] { (byte)0x49, (byte)0x64, (byte)0x76, (byte)0x65, (byte)0x64, (byte)0x65, (byte)0x76, (byte)0x61, (byte)0x6e, (byte)0x20, (byte)0x4d, (byte)0x65, (byte)0x76};
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, 1000, 256 + 128);
Key secretKey = factory.generateSecret(pbeKeySpec);
byte[] test = secretKey.getEncoded();
byte[] key = new byte[32];
byte[] iv = new byte[16];
System.arraycopy(secretKey.getEncoded(), 0, key, 0, 32);
System.arraycopy(secretKey.getEncoded(), 32, iv, 0, 16);
SecretKeySpec secret = new SecretKeySpec(key, "AES");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret, ivSpec);
//Realise Im using UTF16 here! Maybe you need UTF8
byte[] plaintextintobytes =word.getBytes(StandardCharsets.UTF_16LE);
byte[] encrypted = cipher.doFinal(plaintextintobytes);
String encryptedInformation = Base64.encodeToString(encrypted, Base64.NO_WRAP);
return encryptedInformation;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return "";
}
}

java.security.InvalidKeyException: Invalid key length: 8 bytes

I have requirement where I am having a hex key-1122334455667788 and
hex message-2962A83E5D3D5187 to decode with 3des. But when i am trying to decode it ,I am getting error "java.security.InvalidKeyException: Invalid key length: 8 bytes".Please anybody can help?
My code to decrypt
public class TripleDES {
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
public static void main(String[] args) throws Exception {
byte[] keyBytes=hexStringToByteArray("1122334455667788");
byte[] message=hexStringToByteArray("2962A83E5D3D5187");
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
// final byte[] encData = new
// sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
}
}
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.xml.bind.DatatypeConverter;
public class DESede {
private static Cipher encryptCipher;
private static Cipher decryptCipher;
private static byte[] encryptData(String data) throws IllegalBlockSizeException, BadPaddingException {
System.out.println("Data Before Encryption :" + data);
byte[] dataToEncrypt = data.getBytes();
byte[] encryptedData = encryptCipher.doFinal(dataToEncrypt);
System.out.println("Encryted Data: " + encryptedData);
return encryptedData;
}
private static void decryptData(byte[] data) throws IllegalBlockSizeException, BadPaddingException {
byte[] textDecrypted = decryptCipher.doFinal(data);
System.out.println("Decryted Data: " + new String(textDecrypted));
}
public static void main(String[] args) throws InvalidKeySpecException {
try {
String desKey = "0123456789abcdef0123456789abcdef0123456789abcdef"; // Key from user
byte[] keyBytes = DatatypeConverter.parseHexBinary(desKey);
System.out.println((int) keyBytes.length);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
SecretKey key = factory.generateSecret(new DESedeKeySpec(keyBytes));
encryptCipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, key); // throwing Exception
byte[] encryptedData = encryptData("Confidential Data");
decryptCipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
byte iv[] = encryptCipher.getIV();
IvParameterSpec dps = new IvParameterSpec(iv);
decryptCipher.init(Cipher.DECRYPT_MODE, key, dps);
decryptData(encryptedData);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
DESede need 24 bytes key. Try this program.
OUTPUT
Data Before Encryption :Confidential Data
Encryted Data: [B#6fadae5d
Decryted Data: Confidential Data
A triple-DES key is 24 bytes long; see https://docs.oracle.com/javase/7/docs/api/javax/crypto/spec/DESedeKeySpec.html.
(I would try padding the byte array to 24 bytes with zero bytes at the start or end ... and see what works for your cypher text.)
Next problem ...
I tried to change the key to
String desKey = "000000000000000000000000000000001122334455667788";
but I am now getting a "Given final block not properly padded" exception.
I think that is saying that the message is not padded correctly. Try using "NoPadding" instead of "PKCS5Padding".
See
encryption using provided key using DES with padding
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class TripleDES {
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
}
return data;
}
public static void main(String[] args) throws Exception {
byte[] keyBytes = hexStringToByteArray("1122334455667788");
byte[] message = hexStringToByteArray("2962A83E5D3D5187");
final SecretKey key = new SecretKeySpec(keyBytes, "DES");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DES/ECB/NoPadding");
decipher.init(Cipher.DECRYPT_MODE, key);
final byte[] plainText = decipher.doFinal(message);
System.out.println("Decrypted Data :: "+new String(plainText));
}
}
OUTPUT
Decrypted Data :: FB

how to make CBC using DES in java?

Hey everyone i'm about make a program encrypt strings using DES algorithm i want to use CBC mode in this program so i have to make (IV) and XORed it with next Plain Text block
my question is, the (IV) data type is it Byte[] ? and is it enough to add it to the XORed value to the next block and encrypt it ?
this is my code
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class DESEncryption {
private static final String UNICODE_FORMAT = "UTF8";
public static final String DES_ENCRYPTION_SCHEME = "DES";
private KeySpec myKeySpec;
private SecretKeyFactory mySecretKeyFactory;
private Cipher cipher;
byte[] keyAsBytes;
private String myEncryptionKey;
private String myEncryptionScheme;
SecretKey key;
public DESEncryption() throws Exception
{
myEncryptionKey = "ThisIsSecretEncryptionKey";
myEncryptionScheme = DES_ENCRYPTION_SCHEME;
keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
myKeySpec = new DESKeySpec(keyAsBytes);
mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
cipher = Cipher.getInstance(myEncryptionScheme);
key = mySecretKeyFactory.generateSecret(myKeySpec);
}
/**
* <span class="IL_AD" id="IL_AD2">Method</span> To Encrypt The String
*/
public String encrypt(String unencryptedString) {
String encryptedString = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
BASE64Encoder base64encoder = new BASE64Encoder();
encryptedString = base64encoder.encode(encryptedText);
} catch (Exception e) {
e.printStackTrace();
}
return encryptedString;
}
/**
* Method To Decrypt An Ecrypted String
*/
public String decrypt(String encryptedString) {
String decryptedText=null;
try {
cipher.init(Cipher.DECRYPT_MODE, key);
BASE64Decoder base64decoder = new BASE64Decoder();
byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText= bytes2String(plainText);
} catch (Exception e) {
e.printStackTrace();
}
return decryptedText;
}
/**
* Returns String From An Array Of Bytes
*/
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();
}
/**
* Testing the DES Encryption And Decryption Technique
*/
public static void main(String args []) throws Exception
{
DESEncryption myEncryptor= new DESEncryption();
String stringToEncrypt="Sanjaal.com";
String encrypted=myEncryptor.encrypt(stringToEncrypt);
String decrypted=myEncryptor.decrypt(encrypted);
System.out.println("String To Encrypt: "+stringToEncrypt);
System.out.println("Encrypted Value : " + encrypted);
System.out.println("Decrypted Value : "+decrypted);
}
}

How do I use 3DES encryption/decryption in Java?

Every method I write to encode a string in Java using 3DES can't be decrypted back to the original string. Does anyone have a simple code snippet that can just encode and then decode the string back to the original string?
I know I'm making a very silly mistake somewhere in this code. Here's what I've been working with so far:
** note, I am not returning the BASE64 text from the encrypt method, and I am not base64 un-encoding in the decrypt method because I was trying to see if I was making a mistake in the BASE64 part of the puzzle.
public class TripleDESTest {
public static void main(String[] args) {
String text = "kyle boon";
byte[] codedtext = new TripleDESTest().encrypt(text);
String decodedtext = new TripleDESTest().decrypt(codedtext);
System.out.println(codedtext);
System.out.println(decodedtext);
}
public byte[] encrypt(String message) {
try {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;)
{
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
final String encodedCipherText = new sun.misc.BASE64Encoder().encode(cipherText);
return cipherText;
}
catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); }
catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); }
catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); }
catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); }
catch (BadPaddingException e) { System.out.println("Invalid Key");}
catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");}
catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");}
return null;
}
public String decrypt(byte[] message) {
try
{
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;)
{
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
//final byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return plainText.toString();
}
catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); }
catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); }
catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); }
catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); }
catch (BadPaddingException e) { System.out.println("Invalid Key");}
catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");}
catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the contents). Here's a version that's just a teeny bit cleaned up and which prints "kyle boon" as the decoded string:
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class TripleDESTest {
public static void main(String[] args) throws Exception {
String text = "kyle boon";
byte[] codedtext = new TripleDESTest().encrypt(text);
String decodedtext = new TripleDESTest().decrypt(codedtext);
System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
System.out.println(decodedtext); // This correctly shows "kyle boon"
}
public byte[] encrypt(String message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
// final String encodedCipherText = new sun.misc.BASE64Encoder()
// .encode(cipherText);
return cipherText;
}
public String decrypt(byte[] message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
// final byte[] encData = new
// sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
}
Here is a solution using the javax.crypto library and the apache commons codec library for encoding and decoding in Base64:
import java.security.spec.KeySpec;
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 TrippleDes {
private static final String UNICODE_FORMAT = "UTF8";
public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
private KeySpec ks;
private SecretKeyFactory skf;
private Cipher cipher;
byte[] arrayBytes;
private String myEncryptionKey;
private String myEncryptionScheme;
SecretKey key;
public TrippleDes() throws Exception {
myEncryptionKey = "ThisIsSpartaThisIsSparta";
myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
ks = new DESedeKeySpec(arrayBytes);
skf = SecretKeyFactory.getInstance(myEncryptionScheme);
cipher = Cipher.getInstance(myEncryptionScheme);
key = skf.generateSecret(ks);
}
public String encrypt(String unencryptedString) {
String encryptedString = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
encryptedString = new String(Base64.encodeBase64(encryptedText));
} catch (Exception e) {
e.printStackTrace();
}
return encryptedString;
}
public String decrypt(String encryptedString) {
String decryptedText=null;
try {
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedText = Base64.decodeBase64(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText= new String(plainText);
} catch (Exception e) {
e.printStackTrace();
}
return decryptedText;
}
public static void main(String args []) throws Exception
{
TrippleDes td= new TrippleDes();
String target="imparator";
String encrypted=td.encrypt(target);
String decrypted=td.decrypt(encrypted);
System.out.println("String To Encrypt: "+ target);
System.out.println("Encrypted String:" + encrypted);
System.out.println("Decrypted String:" + decrypted);
}
}
Running the above program results with the following output:
String To Encrypt: imparator
Encrypted String:FdBNaYWfjpWN9eYghMpbRA==
Decrypted String:imparator
I had hard times figuring it out myself and this post helped me to find the right answer for my case. When working with financial messaging as ISO-8583 the 3DES requirements are quite specific, so for my especial case the "DESede/CBC/PKCS5Padding" combinations wasn't solving the problem. After some comparative testing of my results against some 3DES calculators designed for the financial world I found the the value "DESede/ECB/Nopadding" is more suited for the the specific task.
Here is a demo implementation of my TripleDes class (using the Bouncy Castle provider)
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
*
* #author Jose Luis Montes de Oca
*/
public class TripleDesCipher {
private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/Nopadding";
private static String ALGORITHM = "DESede";
private static String BOUNCY_CASTLE_PROVIDER = "BC";
private Cipher encrypter;
private Cipher decrypter;
public TripleDesCipher(byte[] key) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
InvalidKeyException {
Security.addProvider(new BouncyCastleProvider());
SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);
encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);
decrypter.init(Cipher.DECRYPT_MODE, keySpec);
}
public byte[] encode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {
return encrypter.doFinal(input);
}
public byte[] decode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {
return decrypter.doFinal(input);
}
}
Here's a very simply static encrypt/decrypt class biased on the Bouncy Castle no padding example by Jose Luis Montes de Oca. This one is using "DESede/ECB/PKCS7Padding" so I don't have to bother manually padding.
package com.zenimax.encryption;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
*
* #author Matthew H. Wagner
*/
public class TripleDesBouncyCastle {
private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/PKCS7Padding";
private static String ALGORITHM = "DESede";
private static String BOUNCY_CASTLE_PROVIDER = "BC";
private static void init()
{
Security.addProvider(new BouncyCastleProvider());
}
public static byte[] encode(byte[] input, byte[] key)
throws IllegalBlockSizeException, BadPaddingException,
NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException, InvalidKeyException {
init();
SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
Cipher encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
BOUNCY_CASTLE_PROVIDER);
encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
return encrypter.doFinal(input);
}
public static byte[] decode(byte[] input, byte[] key)
throws IllegalBlockSizeException, BadPaddingException,
NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException, InvalidKeyException {
init();
SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
Cipher decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
BOUNCY_CASTLE_PROVIDER);
decrypter.init(Cipher.DECRYPT_MODE, keySpec);
return decrypter.doFinal(input);
}
}
private static final String UNICODE_FORMAT = "UTF8";
private static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
private KeySpec ks;
private SecretKeyFactory skf;
private Cipher cipher;
byte[] arrayBytes;
private String encryptionSecretKey = "ThisIsSpartaThisIsSparta";
SecretKey key;
public TripleDesEncryptDecrypt() throws Exception {
convertStringToSecretKey(encryptionSecretKey);
}
public TripleDesEncryptDecrypt(String encryptionSecretKey) throws Exception {
convertStringToSecretKey(encryptionSecretKey);
}
public SecretKey convertStringToSecretKey (String encryptionSecretKey) throws Exception {
arrayBytes = encryptionSecretKey.getBytes(UNICODE_FORMAT);
ks = new DESedeKeySpec(arrayBytes);
skf = SecretKeyFactory.getInstance(DESEDE_ENCRYPTION_SCHEME);
cipher = Cipher.getInstance(DESEDE_ENCRYPTION_SCHEME);
key = skf.generateSecret(ks);
return key;
}
/**
* Encrypt without specifying secret key
*
* #param unencryptedString
* #return String
*/
public String encrypt(String unencryptedString) {
String encryptedString = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
encryptedString = new String(Base64.encodeBase64(encryptedText));
} catch (Exception e) {
e.printStackTrace();
}
return encryptedString;
}
/**
* Encrypt with specified secret key
*
* #param unencryptedString
* #return String
*/
public String encrypt(String encryptionSecretKey, String unencryptedString) {
String encryptedString = null;
try {
key = convertStringToSecretKey(encryptionSecretKey);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
encryptedString = new String(Base64.encodeBase64(encryptedText));
} catch (Exception e) {
e.printStackTrace();
}
return encryptedString;
}
/**
* Decrypt without specifying secret key
* #param encryptedString
* #return
*/
public String decrypt(String encryptedString) {
String decryptedText=null;
try {
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedText = Base64.decodeBase64(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText= new String(plainText);
} catch (Exception e) {
e.printStackTrace();
}
return decryptedText;
}
/**
* Decrypt with specified secret key
* #param encryptedString
* #return
*/
public String decrypt(String encryptionSecretKey, String encryptedString) {
String decryptedText=null;
try {
key = convertStringToSecretKey(encryptionSecretKey);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedText = Base64.decodeBase64(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText= new String(plainText);
} catch (Exception e) {
e.printStackTrace();
}
return decryptedText;
}
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;
import java.util.Base64.Encoder;
/**
*
* #author shivshankar pal
*
* this code is working properly. doing proper encription and decription
note:- it will work only with jdk8
*
*
*/
public class TDes {
private static byte[] key = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02 };
private static byte[] keyiv = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00 };
public static String encode(String args) {
System.out.println("plain data==> " + args);
byte[] encoding;
try {
encoding = Base64.getEncoder().encode(args.getBytes("UTF-8"));
System.out.println("Base64.encodeBase64==>" + new String(encoding));
byte[] str5 = des3EncodeCBC(key, keyiv, encoding);
System.out.println("des3EncodeCBC==> " + new String(str5));
byte[] encoding1 = Base64.getEncoder().encode(str5);
System.out.println("Base64.encodeBase64==> " + new String(encoding1));
return new String(encoding1);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String decode(String args) {
try {
System.out.println("encrypted data==>" + new String(args.getBytes("UTF-8")));
byte[] decode = Base64.getDecoder().decode(args.getBytes("UTF-8"));
System.out.println("Base64.decodeBase64(main encription)==>" + new String(decode));
byte[] str6 = des3DecodeCBC(key, keyiv, decode);
System.out.println("des3DecodeCBC==>" + new String(str6));
String data=new String(str6);
byte[] decode1 = Base64.getDecoder().decode(data.trim().getBytes("UTF-8"));
System.out.println("plaintext==> " + new String(decode1));
return new String(decode1);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "u mistaken in try block";
}
private static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data) {
try {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/ CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] bout = cipher.doFinal(data);
return bout;
} catch (Exception e) {
System.out.println("methods qualified name" + e);
}
return null;
}
private static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) {
try {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/ CBC/NoPadding");//PKCS5Padding NoPadding
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] bout = cipher.doFinal(data);
return bout;
} catch (Exception e) {
System.out.println("methods qualified name" + e);
}
return null;
}
}

Categories

Resources