I want to encrypt decrypt using bouncycastle.
by code sometimes works and sometimes not.
For example for this code:
String msg="ivivivi;message";
String key="1234567891234567";
SecureRandom secureRandom = new SecureRandom();
byte[] keyB = new byte[16];
secureRandom.nextBytes(keyB);
String cipher=Encryption.encrypt(msg.getBytes(),key.getBytes(),keyB);
System.out.println("cipher: "+cipher);
String original=Encryption.decrypt(cipher.getBytes(), key.getBytes(), keyB);
System.out.println("original: "+original);
Expected output:
cipher: c÷cAn‘iµHy~‹eX03
original: ivivivi;message
This gives the output, but if run run the code again and again it sometimes gives the expected result and sometimes not.
when it is not work, it thorws error:
org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted
Here my ecrypt/decrypt functions:
private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data)
throws Exception
{
byte[] result=null;
try{
int minSize = cipher.getOutputSize(data.length);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
int actualLength = length1 + length2;
result = new byte[actualLength];
System.arraycopy(outBuf, 0, result, 0, result.length);
}catch(Exception e){
System.err.println("Encryption [0010] "+e.getMessage());
}
return result;
}
public static String decrypt(byte[] cipher, byte[] key, byte[] iv) throws Exception
{
System.out.println("Encryption decrypt: "+new String(cipher));
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
new AESEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
try {
aes.init(false, ivAndKey);
} catch (Exception e) {
return "";
}
byte[] cip=cipherData(aes, cipher);
if(cip==null){
System.err.println("Encryption.decrypt [0011]: cip is null");
return "";
}
String result=new String(cip);
System.out.println("Encryption decrypted: "+result);
return result;
}
public static String encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception
{
System.out.println("Encryption encrypt: "+new String(plain));
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
new AESEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
aes.init(true, ivAndKey);
return new String(cipherData(aes, plain));
}
what am I missing?
Related
I have one java code that needs to be converted to c# code.
Java Util class
public class EncryptorDecryptorUtil {
private int keySize;
private Cipher cipher;
public EncryptorDecryptorUtil(int keySize)
{
this.keySize = keySize;
try
{
this.cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
}
public String decrypt(String salt, String iv, String passphrase, String EncryptedText)
{
String decryptedValue = null;
try
{
byte[] saltBytes = hexStringToByteArray(salt);
SecretKeySpec sKey = (SecretKeySpec)generateKeyFromPassword(
passphrase, saltBytes);
byte[] ivBytes = hexStringToByteArray(iv);
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
this.cipher.init(2, sKey, ivParameterSpec);
byte[] decordedValue = new BASE64Decoder()
.decodeBuffer(EncryptedText);
byte[] decValue = this.cipher.doFinal(decordedValue);
decryptedValue = new String(decValue);
}
catch (Exception e)
{
e.printStackTrace();
}
return decryptedValue;
}
public static SecretKey generateKeyFromPassword(String password, byte[] saltBytes)
throws GeneralSecurityException
{
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), saltBytes,
100, 128);
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey secretKey = keyFactory.generateSecret(keySpec);
return new SecretKeySpec(secretKey.getEncoded(), "AES");
}
public static byte[] hexStringToByteArray(String s)
{
System.out.println("s:::::::"+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;
}
}
Java Main methods
public class EncryptionDecryption {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONObject json = new JSONObject();
json.put("applicationNo","PNB00000000000004016");
json.put("custID","PNB000000004016");
String input = json.toJSONString();
String password = "46ea428a97ba4c3094fc66e112d1d678";
EncryptionDecryption enc = new EncryptionDecryption();
String encryptMessage= enc.encryptMessage(input, password);
System.out.println("Encrypted Message :"+encryptMessage);
String encrypt2Message = "8b7a1e90d701f55c49e22135eed31c94 89f9af1e83e8c83bdf603f5428ba6f14 0R2A2JDkY8tFR1FZojY7Su9CVI9zjw4yjr/lRElwU75MF5e0LxgOb+Y/DOyVFNd89Ra4YADIZdopLZ5a59Z2BgEjMpSn27tqnGfFvWtfm+eh+A/aVcB2YwfD9rdsd67x6xUb8kmfL7qnO/uxaHyQtqlvwpNRBVjyfRlk1wPfaxyOQa0oEiWRmUXYxEoJ651EhYtHeHKmII7qzDgcioIYUlsBgZUjOu0sNEdiwSvvHbw=";
String decryptMessage = enc.decryptMessage(encrypt2Message, password);
System.out.println("decryptMessage Message :"+decryptMessage);
}
public String encryptMessage(String txtToEncrypt, String passphrase)
{
System.out.println("encryptMessage :txtToEncrypt :"+txtToEncrypt);
String combineData = "";
try
{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
String saltHex = getRandomHexString(32);
String ivHex = getRandomHexString(32);
byte[] salt = hexStringToByteArray(saltHex);
byte[] iv = hexStringToByteArray(ivHex);
SecretKeySpec sKey = (SecretKeySpec)generateKeyFromPassword(
passphrase, salt);
cipher.init(1, sKey, new IvParameterSpec(iv));
byte[] utf8 = txtToEncrypt.getBytes("UTF-8");
byte[] enc = cipher.doFinal(utf8);
combineData = saltHex + " " + ivHex + " " +
new BASE64Encoder().encode(enc);
}
catch (Exception e)
{
e.printStackTrace();
}
combineData = combineData.replaceAll("\n", "").replaceAll("\t", "").replaceAll("\r", "");
return combineData;
}
public String decryptMessage(String str, String myKey)
{
String decrypted = null;
try
{
if ((str != null) && (str.contains(" ")))
{
String salt = str.split(" ")[0];
String iv = str.split(" ")[1];
String encryptedText = str.split(" ")[2];
EncryptorDecryptorUtil dec = new EncryptorDecryptorUtil(128);
decrypted = dec.decrypt(salt, iv, myKey, encryptedText);
}
else
{
decrypted = str;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return decrypted;
}
public static String getRandomHexString(int numchars)
{
Random r = new Random();
StringBuilder sb = new StringBuilder();
while (sb.length() < numchars) {
sb.append(Integer.toHexString(r.nextInt()));
}
return sb.toString().substring(0, numchars);
}
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 SecretKey generateKeyFromPassword(String password, byte[] saltBytes)
throws GeneralSecurityException
{
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), saltBytes,
100, 128);
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey secretKey = keyFactory.generateSecret(keySpec);
return new SecretKeySpec(secretKey.getEncoded(), "AES");
}
}
I have tried below code in .net
public static byte[] hexStringToByteArray(string hexString)
{
byte[] data = new byte[hexString.Length / 2];
for (int index = 0; index < data.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
data[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return data;
}
public string generateKey(String password, byte[] saltBytes)
{
int iterations = 100;
var rfc2898 =
new System.Security.Cryptography.Rfc2898DeriveBytes(password, saltBytes, iterations);
byte[] key = rfc2898.GetBytes(16);
String keyB64 = Convert.ToBase64String(key);
return keyB64;
}
Decrypt method in c#
public string DecryptAlter(string salt, string iv, string passphrase, string EncryptedText)
{
string decryptedValue = null;
try
{
byte[] saltBytes = hexStringToByteArray(salt);
string sKey = generateKey(passphrase, saltBytes);
byte[] ivBytes = hexStringToByteArray(iv);
byte[] keyBytes = System.Convert.FromBase64String(sKey);
AesManaged aesCipher = new AesManaged();
aesCipher.IV = ivBytes;
aesCipher.KeySize = 128;
aesCipher.BlockSize = 128;
aesCipher.Mode = CipherMode.ECB;
aesCipher.Padding = PaddingMode.PKCS7;
byte[] b = System.Convert.FromBase64String(EncryptedText);
ICryptoTransform decryptTransform = aesCipher.CreateDecryptor(keyBytes, ivBytes);
byte[] plainText = decryptTransform.TransformFinalBlock(b, 0, b.Length);
var res = System.Text.Encoding.UTF8.GetString(plainText);
return res;
}
catch (Exception e)
{
var k = e.Message;
}
return "";
}
Its not working. Please help me
The Encryption password is “46ea428a97ba4c3094fc66e112d1d678”
Encrypted Text - 4cdf7b17b7db00d7911498dec913d3e4 1e55c4e950b772685ccfdb831c82fede SCQXvM7GeKxP0jLtX5xbuF0WvBC/C81wwxtYNduUe9lVzaYztaJ8ifivjaCBWd7O2zSa+/A+vtFfdSWSnN5+RcjWka42QQl4f+yZ8C1Y/efIsUlDVXBXmSEjSUp/4sflXNz7qg62Ka+atpj0aiG6QvU+T5tnafmsDhx/M3zE+Tg=
Now need to decrypt it.
This is what I got so far to guide you towards a final solution. The encrypted message contains a salt and iv that need to be extracted then used to decrypt the message.
using System;
using System.Globalization;
using System.Security.Cryptography;
public class Program
{
public static void Main()
{
string password = "46ea428a97ba4c3094fc66e112d1d678";
string encrypt2Message = "8b7a1e90d701f55c49e22135eed31c94 89f9af1e83e8c83bdf603f5428ba6f14 0R2A2JDkY8tFR1FZojY7Su9CVI9zjw4yjr/lRElwU75MF5e0LxgOb+Y/DOyVFNd89Ra4YADIZdopLZ5a59Z2BgEjMpSn27tqnGfFvWtfm+eh+A/aVcB2YwfD9rdsd67x6xUb8kmfL7qnO/uxaHyQtqlvwpNRBVjyfRlk1wPfaxyOQa0oEiWRmUXYxEoJ651EhYtHeHKmII7qzDgcioIYUlsBgZUjOu0sNEdiwSvvHbw=";
string[] pieces = encrypt2Message.Split(' ');
string salt = pieces[0];
string iv = pieces[1];
string encmessage = pieces[2];
string decryptMessage = DecryptAlter( salt, iv, password, encmessage);
Console.WriteLine("decryptMessage Message :"+decryptMessage);
}
public static byte[] hexStringToByteArray(string hexString)
{
byte[] data = new byte[hexString.Length / 2];
for (int index = 0; index < data.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
data[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return data;
}
public static string generateKey(String password, byte[] saltBytes)
{
int iterations = 100;
var rfc2898 =
new System.Security.Cryptography.Rfc2898DeriveBytes(password, saltBytes, iterations);
byte[] key = rfc2898.GetBytes(16);
String keyB64 = Convert.ToBase64String(key);
return keyB64;
}
public static string DecryptAlter(string salt, string iv, string passphrase, string EncryptedText)
{
string decryptedValue = null;
try
{
byte[] saltBytes = hexStringToByteArray(salt);
string sKey = generateKey(passphrase, saltBytes);
byte[] ivBytes = hexStringToByteArray(iv);
byte[] keyBytes = System.Convert.FromBase64String(sKey);
AesManaged aesCipher = new AesManaged();
aesCipher.IV = ivBytes;
aesCipher.KeySize = 128;
aesCipher.BlockSize = 128;
aesCipher.Mode = CipherMode.CBC;
aesCipher.Padding = PaddingMode.PKCS7;
byte[] b = System.Convert.FromBase64String(EncryptedText);
ICryptoTransform decryptTransform = aesCipher.CreateDecryptor(keyBytes, ivBytes);
byte[] plainText = decryptTransform.TransformFinalBlock(b, 0, b.Length);
var res = System.Text.Encoding.UTF8.GetString(plainText);
return res;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
return "";
}
}
public string decryptMessage()
{
string str="some encrypted message";
string myKey = "46ea428a97ba4c3094fc66e112d1d678";
string decrypted = null;
try
{
if ((str != null) && (str.Contains(' ')))
{
string salt = str.Split(' ')[0];
string iv = str.Split(' ')[1];
String encryptedText = str.Split(' ')[2];
decrypted = DecryptAlter(salt, iv, myKey, encryptedText);
return decrypted;
}
else
{
decrypted = str;
return decrypted;
}
}
catch (Exception e)
{
}
return decrypted;
}
public string DecryptAlter(string salt, string iv, string passphrase, string EncryptedText)
{
string decryptedValue = null;
try
{
byte[] saltBytes = hexStringToByteArray(salt);
string sKey = generateKey(passphrase, saltBytes);
byte[] ivBytes = hexStringToByteArray(iv);
byte[] keyBytes = System.Convert.FromBase64String(sKey);
AesManaged aesCipher = new AesManaged();
aesCipher.IV = ivBytes;
aesCipher.KeySize = 128;
aesCipher.BlockSize = 128;
aesCipher.Mode = CipherMode.CBC;
aesCipher.Padding = PaddingMode.PKCS7;
byte[] b = System.Convert.FromBase64String(EncryptedText);
ICryptoTransform decryptTransform = aesCipher.CreateDecryptor(keyBytes, ivBytes);
byte[] plainText = decryptTransform.TransformFinalBlock(b, 0, b.Length);
var res = System.Text.Encoding.UTF8.GetString(plainText);
return res;
}
catch (Exception e)
{
var k = e.Message;
}
return "";
}
Recently i've post a question about this topic but the thing turns a little weird when i tried to decrypt an AES String that was encoded on UTF8
In the following lines i read the String AES encrypted wich returns the following String: RnLObq9hdUDGp9S2pxC1qjQXekuf9g6i/5bQfKilYn4=
public static final String AesKey256 ="ZzRtNDNuY3J5cHRrM3kuLi4=";
//This reads the String and stores on res.getContents()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult res= IntentIntegrator.parseActivityResult(requestCode, resultCode,data);
if(res!=null){
if (res.getContents() == null) {
Toast.makeText(this,"Captura cancelada",Toast.LENGTH_SHORT).show();
}else{
try {
String cadena= decrypt(res.getContents());
out.setText(cadena);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//provide the res.getContents() to decrypt method, wich its the String i've recently read
private String decrypt(String cadena)throws Exception{
SecretKeySpec keySpec= generateKey(AesKey256); //HERE
Cipher c= Cipher.getInstance(AES_MODE);
c.init(Cipher.DECRYPT_MODE,keySpec);
byte[] decodedValue= Base64.decode(cadena, Base64.DEFAULT);
byte[] decValue= c.doFinal(decodedValue);/* c.doFinal(decodedValue);*/
String decryptedValue= new String((decValue), "UTF-8");
return decryptedValue;
}
private SecretKeySpec generateKey(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
final MessageDigest digest= MessageDigest.getInstance("SHA-256");
byte[] bytes= password.getBytes("UTF-8");
digest.update(bytes,0,bytes.length);
byte[] key= digest.digest();
SecretKeySpec secretKeySpec= new SecretKeySpec(key, "AES");
return secretKeySpec;
}
I am only using the decryption method but it still returning this characters:
i've spent hours looking for a solution, but nothing works for now... hope someone can give me a hand!
Best Regards!
EDIT
THIS IS HOW IT WAS ENCRYPTED IN C#
private const string AesIV256 = "IVFBWjJXU1gjRURDNFJGVg==";
private const string AesKey256 = "ZzRtNDNuY3J5cHRrM3kuLi4=";
public static string Encrypt(string text)
{
var sToEncrypt = text;
var rj = new RijndaelManaged()
{
Padding = PaddingMode.Zeros,
Mode = CipherMode.ECB,
KeySize = 256,
BlockSize = 256,
};
var key = Convert.FromBase64String(AesKey256);
var IV = Convert.FromBase64String(AesIV256);
var encryptor = rj.CreateEncryptor(key, IV);
var msEncrypt = new MemoryStream();
var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
var toEncrypt = Encoding.UTF8.GetBytes(sToEncrypt);
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();
var encrypted = msEncrypt.ToArray();
return (Convert.ToBase64String(encrypted));
}
Made it!
After a long time of searching thanks to all you guys who answered this post i used the bouncy castle library and i've decrypt the desired String by doing the following:
public static String decrypt(String valueToDecrypt) throws Exception {
AESCrypt enc = new AESCrypt();
return new String(enc.decryptInternal(valueToDecrypt)).trim();
}
private byte[] decryptInternal(String code) throws Exception {
if (code == null || code.length() == 0) {
throw new Exception("Empty string");
}
byte[] decrypted = null;
try {
byte[] key= SecretKey.getBytes("UTF-8");
PaddedBufferedBlockCipher c = new PaddedBufferedBlockCipher(new RijndaelEngine(256), new ZeroBytePadding());
CipherParameters params= new KeyParameter(key);`
// false because its going to decrypt
c.init(false,params);
decrypted= GetData(c,(Base64.decode(code,Base64.DEFAULT));
} catch (Exception e) {
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}
private static byte[] GetData(PaddedBufferedBlockCipher cipher, byte[] data) throws InvalidCipherTextException
{
int minSize = cipher.getOutputSize(data.length);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
int actualLength = length1 + length2;
byte[] cipherArray = new byte[actualLength];
for (int x = 0; x < actualLength; x++) {
cipherArray[x] = outBuf[x];
}
return cipherArray;
}
I am trying to write an encryption/decryption utility class, but not matter what I do I cannot seem to get decryption working. I keep getting a javax.crypto.BadPaddingException: Given final block not properly padded exception during decryption.
I've looked at a number of examples and other stack overflow questions but can't seem to find my mistake
public class EncryptionUtil {
private static final Log LOGGER = LogFactory.getLog(EncryptionUtil.class);
private static final String CIPHER_MODE = "AES/CBC/PKCS5PADDING";
private static final String CRYPTO_PROPERTIES_PATH = "/crypto.properties";
private static final SecretKeySpec sKey = keySpecFromProperties();
private EncryptionUtil() {}
public static byte[] encrypt(byte[] aBytes) {
try {
SecureRandom lSecureRandom = new SecureRandom();
byte[] ivBytes = new byte[16];
lSecureRandom.nextBytes(ivBytes);
IvParameterSpec lSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance(CIPHER_MODE);
cipher.init(Cipher.ENCRYPT_MODE, sKey, lSpec);
byte[] encryptedBytes = cipher.doFinal(aBytes);
byte[] outBytes = new byte[encryptedBytes.length + 16];
System.arraycopy(ivBytes, 0, outBytes, 0, 16);
System.arraycopy(encryptedBytes, 0, outBytes, 16, encryptedBytes.length);
return outBytes;
} catch (Exception aEx) {
LOGGER.error("Failed to encrypt bytes");
throw new RuntimeException(aEx);
}
}
public static byte[] decrypt(byte[] aBytes) {
try {
byte[] lIvBytes = Arrays.copyOfRange(aBytes, aBytes.length - 16, aBytes.length);
byte[] lEncryptedBytes = Arrays.copyOfRange(aBytes, 0, aBytes.length - 16);
IvParameterSpec lIvSpec = new IvParameterSpec(lIvBytes);
Cipher cipher = Cipher.getInstance(CIPHER_MODE);
cipher.init(Cipher.DECRYPT_MODE, sKey, lIvSpec);
return cipher.doFinal(lEncryptedBytes);
}catch (Exception aEx){
LOGGER.error("Failed to decrypt bytes. Returning input bytes", aEx);
return aBytes;
}
}
private static SecretKeySpec keySpecFromProperties(){
try(InputStream lPropStream = EncryptionUtil.class.getResourceAsStream(CRYPTO_PROPERTIES_PATH)){
Properties cryptoProps = new Properties();
cryptoProps.load(lPropStream);
String lSecret = cryptoProps.getProperty("secret");
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(lSecret.getBytes("UTF-8"));
byte[] keyBytes = new byte[16];
System.arraycopy(digest.digest(),0, keyBytes, 0, keyBytes.length);
return new SecretKeySpec(keyBytes, "AES");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
You prepend your IV to the ciphertext on encryption, but on decryption you copy the last 16 bytes as your IV.
Whatever you do on encryption you must undo on decryption.
' Encrypts a string using tripple DES
Private Function TripleDESEncrypt(ByVal str As String) As TripleDESEncryptResult
' 3DES Encryption
' Generate KEY/IV pair for your local 3DES encrpytion on xmlCard
' Create a new 3DES CryptoProvider and generate KEY/IV pair for encryption
Dim m_cryptoProvider As New TripleDESCryptoServiceProvider
m_cryptoProvider.GenerateIV()
m_cryptoProvider.GenerateKey()
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream
Dim cryptoStream As CryptoStream = _
New CryptoStream(stream, m_cryptoProvider.CreateEncryptor, _
CryptoStreamMode.Write)
Dim Input() As Byte = System.Text.Encoding.Default.GetBytes(str)
cryptoStream.Write(Input, 0, Input.Length)
cryptoStream.FlushFinalBlock()
' Convert to base64, so it'll be XML-friendly
Dim encryptedCardString = System.Convert.ToBase64String(stream.ToArray())
cryptoStream.Close()
cryptoStream.Dispose()
Return New TripleDESEncryptResult(encryptedCardString, m_cryptoProvider.Key, m_cryptoProvider.IV)
End Function
Below code is in java for 3DES encryption and decryption. please try with this code. I hope it will help you
private static final String UNICODE_FORMAT = "UTF8";
public static final String DESEDE_ENCRYPTION_SCHEME = "DESede"; //"DESede/ECB/NoPadding";
private KeySpec ks;
private SecretKeyFactory skf;
private Cipher cipher;
byte[] arrayBytes;
private String myEncryptionKey;
private String myEncryptionScheme;
SecretKey key;
public PasswordEncryption_TrippleDES() throws Exception {
myEncryptionKey = "ThisIsSpartaThisIsanilku";
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
{
PasswordEncryption_TrippleDES td= new PasswordEncryption_TrippleDES();
String target="data for encyption";
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);
}
I am using this class to encrypt a string in android app
public class Encryption {
public static String encrypt(String seed, String cleartext) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String seed, String encrypted) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
}
I am using above class like this -
Encryption.encrypt("password", "some text to be encrypted");
Their is no problem in encrypting the string, but when i try to decrypt the encrypted string (using the same class i posted above) in external java program (not in android app),
Encryption.decrypt("password","D4036388D459C4009812FB3F1AE4BB36E4419C97775D");
i get this exception -
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at Encryption.decrypt(Encryption.java:59)
at Encryption.decrypt(Encryption.java:32)
at Encryption.main(Encryption.java:96)
I think, this is because i am using same code on different platforms,
But i don't know proper reason why this doesn't work ? and
Is their any way i can decrypt the string in java?
#SteveP is probably right.
Still another problem I see, is the byte[] getBytes("UTF-8") (binary data) to String new String(bytes, "UTF-8") (text) conversion. On Android the default encoding is UTF-8, on Windows most likely something else.