Really a buggy question , hee is the code:
import java.io.IOException;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Encryption {
public static final int a = 0x9F224;
public static final int b = 0x98C36;
public static final int c = 0x776a2;
public static final int d = 0x87667;
private String preMaster;
IvParameterSpec ivSpec = new IvParameterSpec(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01 });
private byte[] text;
private SecretKey secret;
private byte[] sKey;
protected SecretKey passwordKey;
protected PBEParameterSpec paramSpec;
public static final String ENCYT_ALGORITHM = "AES/CBC/PKCS7Padding";
public static final String KEY_ALGORITHM = "PBEWITHSHA256AND256BITAES-CBC-BC" ;
//BENCYT_ALGORITHMSE64Encoder encod = new BENCYT_ALGORITHMSE64Encoder();
//BENCYT_ALGORITHMSE64Decoder decod = new BENCYT_ALGORITHMSE64Decoder();
public Encryption(String preMaster,String text,int x){
this.preMaster=preMaster;
this.text=Encoder.decode(text.toCharArray());
try {
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(256);
secret = kg.generateKey();
} catch (Exception e) {
// TODO ENCYT_ALGORITHMuto-generated catch block
e.printStackTrace();
}
}
public Encryption(String key,String text){
try {
this.text = Encoder.decode(text.toCharArray());
this.sKey = Encoder.decode(key.toCharArray());
} catch (Exception e) {
e.printStackTrace();
}
}
public String preMaster() {
byte[] keys = null;
keys = preMaster.getBytes();
int x = -1;
int process = 0;
while (x < keys.length - 2) {
x++;
switch (x) {
case 1:
process = keys[x + 1] | a ^ c & (d | keys[x] % a);
case 2:
process += a | (keys[x] ^ c) & d;
case 3:
process += keys[x] ^ (keys[x + 1] / a) % d ^ b;
default:
process += keys[x + 1] / (keys[x] ^ c | d);
}
}
byte[] xs = new byte[] { (byte) (process >>> 24),
(byte) (process >> 16 & 0xff), (byte) (process >> 8 & 0xff),
(byte) (process & 0xff) };
preMaster = new String(xs);
KeyGenerators key = new KeyGenerators(preMaster);
String toMaster = key.calculateSecurityHash("MD5")
+ key.calculateSecurityHash("MD2")
+ key.calculateSecurityHash("SHA-512");
return toMaster;
}
public String keyWrapper(){
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Key SharedKey = secret;
String key = null;
char[] preMaster = this.preMaster().toCharArray();
try {
byte[]salt={ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
paramSpec = new PBEParameterSpec(salt,20);
PBEKeySpec keySpec = new PBEKeySpec(preMaster);
SecretKeyFactory factory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
passwordKey = factory.generateSecret(keySpec);
Cipher c = Cipher.getInstance(KEY_ALGORITHM);
c.init(Cipher.WRAP_MODE, passwordKey, paramSpec);
byte[] wrappedKey = c.wrap(SharedKey);
key=Encoder.encode(wrappedKey);
}catch(Exception e){
e.printStackTrace();
}
return key;
}
public Key KeyUnwrapper(){
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
byte[] wrappedKey = sKey;
Key unWrapped = null;
try{
Cipher c = Cipher.getInstance(KEY_ALGORITHM,"BC");
c.init(Cipher.UNWRAP_MODE, passwordKey, paramSpec);
unWrapped = c.unwrap(wrappedKey, ENCYT_ALGORITHM, Cipher.SECRET_KEY);
}catch(Exception e){
e.printStackTrace();
}
return unWrapped;
}
public String encrypt(){
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
SecretKey key = secret;
String result=null;
try{
Cipher cipher = Cipher.getInstance(ENCYT_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
result =Encoder.encode(cipher.doFinal(text));
}catch(Exception e){
e.printStackTrace();
}
return result;
}
public String decrypt(){
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
String result = null;
SecretKey key = (SecretKey) KeyUnwrapper();
try{
Cipher cipher = Cipher.getInstance(ENCYT_ALGORITHM, "BC");
cipher.init(Cipher.DECRYPT_MODE, key);
result = Encoder.encode(cipher.doFinal(text));
}catch(Exception e){
e.printStackTrace();
}
return result;
}
public static void main(String[] args) throws IOException{
Encryption en = new Encryption("123456","Hello World",0);
String enText = en.encrypt();
String key = en.keyWrapper();
System.out.println(key);
System.out.println(enText);
Encryption de = new Encryption(key,enText);
String plainText = de.decrypt();
System.out.println(plainText);
}
And , this is the result ... i tried all the combinations i can, but none of them works ..
F63DE3EE8CEECF4DF76836CA6D69A3903BD87B5726656C54C1C8EC30B6653B2C0E5C7672BE3CF4BE7B2DC7AC5D07DEA0
F1C8D92E5F74019C569D54D70045ADD6
java.lang.NullPointerException
at org.bouncycastle.jce.provider.JCEBlockCipher.engineInit(Unknown Source)
at javax.crypto.Cipher.init(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at fiador.authentication.util.Encryption.KeyUnwrapper(Encryption.java:114)
at fiador.authentication.util.Encryption.decrypt(Encryption.java:142)
at fiador.authentication.util.Encryption.main(Encryption.java:160)
java.lang.NullPointerException
at org.bouncycastle.jce.provider.JCEBlockCipher.engineInit(Unknown Source)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at fiador.authentication.util.Encryption.decrypt(Encryption.java:145)
at fiador.authentication.util.Encryption.main(Encryption.java:160)
null
The first NullPointerException occurs inside this method call (in the KeyUnwrapper method):
c.init(Cipher.UNWRAP_MODE, passwordKey, paramSpec);
Have a look: Could one of these arguments be null?
Looking at the code, it seems like passwordKey is only assigned to in keyWrapper, but this is not called on this instance of your class.
Related
I am using a C# "encrypt" and need a Java "decrypt" method. I need help in java that i can't replicate C# decryption on java and it is not explicit Padding on C# , i don't know what use in java and my key size I think is different but I am not sure. I'm very confused.
know that i need change Java Policy , and did it ! and Change Key size JAVA to 32 bytes.
C#
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Voa.Cross.Util.Extensions;
namespace Voa.Core.Safeties
{
public class Security
{
private readonly string _defaultKey = "sjkdhfjksdhf3444KDFK4nFLFGKdsnjcnj2cmkeKDIK484dmd999sksksksUUddUZ83k030394m49jdjPuWzRk8Zq2PfnpR3YrYWSq2AaUT6meeC3tr36nTVkuudKWbDyPjhUwbwXBzkUhSPKPpSRheR49em4qJWa6YHSCjKX3K93FEMnqXhYauXwjJwbHXfPWTSdxy6ebCBPyAfqk7Uz5nrRddVjZrxWNCMZYG3PbcvPWA34ekdkd454ldnvJKl";
private readonly int _divisionKey = 4;
private readonly byte[] _iv = new byte[16] {0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c};
private byte[] _key;
public Security() => _key = SHA256.Create().ComputeHash(Encoding.ASCII.GetBytes(_defaultKey));
public string Encrypt(string data, string key)
{
if (!string.IsNullOrEmpty(key))
{
CustomKey(key);
}
var encryptor = Aes.Create();
encryptor.Mode = CipherMode.CBC;
// Set key and IV
var aesKey = new byte[32];
Array.Copy(_key, 0, aesKey, 0, 32);
encryptor.Key = aesKey;
encryptor.IV = _iv;
var memoryStream = new MemoryStream();
var aesEncryptor = encryptor.CreateEncryptor();
var cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);
var plainBytes = Encoding.ASCII.GetBytes(data);
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
cryptoStream.FlushFinalBlock();
var cipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
var cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
return cipherText;
}
public string Decrypt(string data, string key)
{
if (!string.IsNullOrEmpty(key))
{
CustomKey(key);
}
var encryptor = Aes.Create();
encryptor.Mode = CipherMode.CBC;
var aesKey = new byte[32];
Array.Copy(_key, 0, aesKey, 0, 32);
encryptor.Key = aesKey;
encryptor.IV = _iv;
var memoryStream = new MemoryStream();
var aesDecryptor = encryptor.CreateDecryptor();
var cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Write);
var plainText = string.Empty;
try
{
var cipherBytes = Convert.FromBase64String(data);
cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);
cryptoStream.FlushFinalBlock();
var plainBytes = memoryStream.ToArray();
plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
}
finally
{
memoryStream.Close();
cryptoStream.Close();
}
return plainText;
}
private void CustomKey(string key)
{
var blockSize = key.Length / _divisionKey;
var splitKey = key.CutString(blockSize).ToList();
var splitDefaultKey = _defaultKey.CutString(blockSize).ToList();
var newKey = string.Concat(splitDefaultKey.Intertwine(splitKey).ToList());
_key = SHA256.Create().ComputeHash(Encoding.ASCII.GetBytes(newKey));
}
}
}
JAVA test...
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SecurityAESEncryption {
private static final String _key = "sjkdhfjksdhf3444KDFK4nFLFGKdsnjcnj2cmkeKDIK484dmd999sksksksUUddUZ83k030394m49jdjPuWzRk8Zq2PfnpR3YrYWSq2AaUT6meeC3tr36nTVkuudKWbDyPjhUwbwXBzkUhSPKPpSRheR49em4qJWa6YHSCjKX3K93FEMnqXhYauXwjJwbHXfPWTSdxy6ebCBPyAfqk7Uz5nrRddVjZrxWNCMZYG3PbcvPWA34ekdkd454ldnvJKl";
private static final char[] initCharArray = new char[] {0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c};
private static final byte[] initVector = SecurityAESEncryption.charToByteArray(initCharArray);
//private static final String initArray = "26dcff00aded7aeec5fe07af4d08223c";
//private static final byte[] ivValue = SecurityAESEncryption.hexStringToByteArray(initArray);
//private static final byte[] key = DigestUtils.sha256(_key.getBytes(StandardCharsets.US_ASCII)).;
private static final byte[] key = SecurityAESEncryption.computeHash(_key);
public static String encrypt(String value) {
try {
System.out.println(key.length);
System.out.println(Base64.decodeBase64(key).length);
byte[] aesKey = new byte[32];
System.arraycopy(key, 0, aesKey, 0, 32);
SecretKeySpec skeySpec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(initVector);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
return Base64.encodeBase64String(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String encrypted) {
try {
byte[] encryptedBytes = Base64.decodeBase64(encrypted);
System.out.println(key.length);
System.out.println(Base64.decodeBase64(key).length);
byte[] aesKey = new byte[32];
System.arraycopy(key, 0, aesKey, 0, 32);
IvParameterSpec iv = new IvParameterSpec(initVector);
SecretKeySpec skeySpec = new SecretKeySpec(aesKey, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
//byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
byte[] original = cipher.doFinal(encryptedBytes);
return new String(original,StandardCharsets.US_ASCII);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static byte[] charToByteArray(char[] x)
{
final byte[] res = new byte[x.length];
for (int i = 0; i < x.length; i++)
{
res[i] = (byte) x[i];
}
return res;
}
public static byte[] computeHash(String input) {
try {
// Static getInstance method is called with hashing SHA
MessageDigest md = MessageDigest.getInstance("SHA-256");
return md.digest(input.getBytes(StandardCharsets.US_ASCII));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
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) {
String originalString = "123456!##";
System.out.println("Original String to encrypt - " + originalString);
String encryptedString = encrypt(originalString);
System.out.println("Encrypted String - " + encryptedString);
String decryptedString = decrypt("Ci10C7ZjUPoEnitdh7QkEw==");
System.out.println("After decryption - " + decryptedString);
}
Your edited Java prog now successfully encrypts the string "123456!##" to this (Base64 encoded) string "LnZV0Vph+eUeJLT2Gst0kw==" using a String as input to a SHA-256 digest, so the real key used for en-/decryption is
(hex) "07c3491eaa6a6289ca91b7b0f290d60688538860b44753f1cf9617977985d2db".
Using this encoded string as input for your decrypt method returns the original string but when using the encoded/encrypted
string "Ci10C7ZjUPoEnitdh7QkEw==" I'm running into this exception:
javax.crypto.BadPaddingException: Given final block not properly padded.
Such issues can arise if a bad key is used during decryption.
Imho this indicates that the key your're using on Java-side is not the same as on C#-side (we don't see the real input
to Encrypt and I don't know what "CustomKey" is doing :-).
Could you please print out
the aeskey and -iv from your C#-Encrypt method directly after you setup them in encryptor-inits and share them here,
that might be usefull for us to help.
public string Encrypt(string data, string key)
...
// Set key and IV
var aesKey = new byte[32];
Array.Copy(_key, 0, aesKey, 0, 32);
encryptor.Key = aesKey;
encryptor.IV = _iv;
==> print aesKey & _iv
...
Help me on Java equivalent of PHP AES Encryption.
I tried with java AES encryption it was working but the below equivalent php code not giving correct encryption decryption with java
I have given php and equivalent java code, but result is not expected one.
PHP code:
function encrypt($plainText)
{
$key='12345678912345671234567891234567'; //size 32
$md5=md5($key);
$plainText='I am plain text';
$secretKey = hextobin($md5);
$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
$openMode = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '','cbc', '');
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, 'cbc');
$plainPad = pkcs5_pad($plainText, $blockSize);
if (mcrypt_generic_init($openMode, $secretKey, $initVector) != -1)
{
$encryptedText = mcrypt_generic($openMode, $plainPad);
mcrypt_generic_deinit($openMode);
}
$data = bin2hex($encryptedText);
return $data;
}
function decrypt($encryptedText)
{
$key='12345678912345671234567891234567';
$md5=md5($key);
$secretKey = hextobin($md5);
$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
$encryptedText=hextobin($encryptedText);
$openMode = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '','cbc', '');
mcrypt_generic_init($openMode, $secretKey, $initVector);
$decryptedText = mdecrypt_generic($openMode, $encryptedText);
$decryptedText = rtrim($decryptedText, "\0");
mcrypt_generic_deinit($openMode);
return $decryptedText;
}
//*********** Padding Function *********************
function pkcs5_pad ($plainText, $blockSize)
{
$pad = $blockSize - (strlen($plainText) % $blockSize);
return $plainText . str_repeat(chr($pad), $pad);
}
//********** Hexadecimal to Binary function for php 4.0 version ********
function hextobin($hexString)
{
$length = strlen($hexString);
$binString="";
$count=0;
while($count<$length)
{
$subString =substr($hexString,$count,2);
$packedString = pack("H*",$subString);
if ($count==0)
{
$binString=$packedString;
}
else
{
$binString.=$packedString;
}
$count+=2;
}
return $binString;
}
Java code:
public class StatusAES2 {
private static final String key = "12345678912345671234567891234567";
public static void main(String[] args) {
String plainText = "I am plain text";
System.out.println("Original String to encrypt - " + plainText);
String encryptedString = encrypt(plainText);
System.out.println("Encrypted String - " + encryptedString);
String decryptedString = decrypt(encryptedString);
System.out.println("After decryption - " + decryptedString);
}
public static String encrypt(String value) {
try {
byte[] keybytes=key.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(keybytes);
String md5Str=Hex.encodeHexString(thedigest);
IvParameterSpec iv = new IvParameterSpec(new byte[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15});
keybytes=hextobin(md5Str).getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(keybytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
String encryptedText=Hex.encodeHexString(encrypted);//bin2hex
return encryptedText;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String encrypted) {
try {
byte[] keybytes=key.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(keybytes);
String md5Str=Hex.encodeHexString(thedigest);
IvParameterSpec iv = new IvParameterSpec(new byte[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15});
keybytes=hextobin(md5Str).getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(keybytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(Hex.decodeHex(encrypted.toCharArray()));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String hextobin(String s) throws DecoderException, UnsupportedEncodingException {
int length=s.length();
int count=0;
String binString="";
while(count<length){
int c=count+2;
String subs=s.substring(count,c);
String packedString="";
byte[] somevar = DatatypeConverter.parseHexBinary(subs);
byte[] bytes = Hex.decodeHex(subs.toCharArray());
packedString=new String(bytes, "UTF-8");
if (count==0){
binString=packedString;
}else {
binString=binString+packedString;
}
count=count+2;
}
return binString;
}
}
Add this dependency.
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
Try this
CBCBlockCipher cbcBlockCipher = new CBCBlockCipher(new AESEngine());
SecureRandom random = new SecureRandom();
KeyParameter key = new KeyParameter(yourSecretKey);
BlockCipherPadding blockCipherPadding = new PKCS7Padding();
PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(cbcBlockCipher, blockCipherPadding);
private byte[] processing(byte[] input, boolean encrypt) throws DataLengthException, InvalidCipherTextException {
int blockSize = cbcBlockCipher.getBlockSize();
int inputOffset = 0;
int inputLength = input.length;
int outputOffset = 0;
byte[] initializationVector = new byte[blockSize];
if (encrypt) {
random.nextBytes(initializationVector);
outputOffset += blockSize;
} else {
System.arraycopy(input, 0, initializationVector, 0, blockSize);
inputOffset += blockSize;
inputLength -= blockSize;
}
pbbc.init(encrypt, new ParametersWithIV(key, initializationVector));
byte[] output = new byte[pbbc.getOutputSize(inputLength) + outputOffset];
if (encrypt) {
System.arraycopy(initializationVector, 0, output, 0, blockSize);
}
int outputLength = outputOffset + pbbc.processBytes(input, inputOffset, inputLength, output, outputOffset);
outputLength += pbbc.doFinal(output, outputLength);
return Arrays.copyOf(output, outputLength);
}
I am using this class for encoding/decoding:
public class enc_dec {
public static Cipher dcipher, ecipher;
public enc_dec() {
byte[] salt = { (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
(byte) 0x56, (byte) 0x34, (byte) 0xE3, (byte) 0x03 };
int iterationCount = 19;
try {
// Generate a temporary key. In practice, you would save this key
// Encrypting with DES Using a Pass Phrase
KeySpec keySpec = new PBEKeySpec("".toCharArray(), salt,iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES")
.generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameters to the cipthers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt,
iterationCount);
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (Exception e) { }
}
// Encrpt Password
#SuppressWarnings("unused")
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (Exception e) {
}
return null;
}
// Decrpt password
// To decrypt the encryted password
public String decrypt(String str) {
Cipher dcipher = null;
try {
byte[] salt = { (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
(byte) 0x56, (byte) 0x34, (byte) 0xE3, (byte) 0x03 };
int iterationCount = 19;
try {
String passPhrase = "";
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(),
salt, iterationCount);
SecretKey key = SecretKeyFactory
.getInstance("PBEWithMD5AndDES")
.generateSecret(keySpec);
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameters to the cipthers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt,
iterationCount);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (Exception e) {}
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (Exception e) {
}
return null;
}
This is my URL-which i am sending from a JSP page:
http://localhost:8080/Sample_Project/send_encode.ENC?type=M0z7jTCb8PPfSZxfAdhw3Q==&payment=UxCU5BdZh4U=&sr_no=eN1X3XOeYuI=
This is my send_encode servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession(false);
if(session.getAttribute("session_set")!=null)
{
classes.enc_dec enc=new classes.enc_dec();
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
String type=enc.decrypt(request.getParameter("type"));
String payment=enc.decrypt(request.getParameter("payment"));
long sr_no=Long.parseLong(request.getParameter("sr_no"));
try{
RequestDispatcher comprd = getServletContext().getRequestDispatcher("/new_page.jsp?type="+enc.encrypt(type)+"&payment="+enc.encrypt(payment)+"");
comprd.include(request, response);
}
catch(Exception e)
{
System.out.println("The ecxeption is "+e);
}
}
The exception I am facing is:
WARNING: StandardWrapperValve[send_encode]: Servlet.service() for servlet send_encode threw exception
java.lang.NumberFormatException: For input string: "eN1X3XOeYuI="
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:441)
at java.lang.Long.parseLong(Long.java:483)
at controller.send_encode.doGet(send_encode.java:30)
I have set encoding as UTF-8 but still i am getting the exception.I have also tried other questions posted on SO but unable to get any help.
Thanks in advance
I'm trying to code a crypto java testclass which encrypt and decrypt a String password with BouncyCastle. The main() is very simple, I do encryptPass() and then decryptPass(), and I watch the console trace.
The problem is when it tries to decrypt, I got a padding exception :
javax.crypto.BadPaddingException: pad block corrupted
at org.bouncycastle.jce.provider.JCEBlockCipher.engineDoFinal(Unknown Source)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at com.kiengi.crypto.Crypto.decryptPass(Crypto.java:79)
My code is the following for the Crypto class :
// password to be crypted
public String pass = "password_go_here";
// key for encrypt pass
public String passKey = generateRandomKey(); // generation clef 16 caractere [a-zA-Z0-9]
// Encrypted pass
public String cryptedPass;
public final Logger logger = Logger.getLogger(this.getClass());
private final static byte[] IV_BYTES = new byte[] { 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01,
0x00, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00 };
public Crypto() {
super();
}
public void encryptPass(){
Security.addProvider(new BouncyCastleProvider());
IvParameterSpec _ivSpec = new IvParameterSpec(IV_BYTES);
try{
KeyGenerator _keygen = KeyGenerator.getInstance("AES");
_keygen.init(new SecureRandom(passKey.getBytes()));
SecretKey _key = _keygen.generateKey();
logger.trace("Secret key generated");
Cipher _cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
_cipher.init(Cipher.ENCRYPT_MODE, _key, _ivSpec);
cryptedPass = asHex(_cipher.doFinal(pass.getBytes("UTF-8")));
logger.trace("Encrypted pass : "+cryptedPass);
}catch (Exception e) {
logger.warn("encrypt failed");
e.printStackTrace();
}
}
public void decryptPass() {
byte[] _passKey = passKey.getBytes();
byte[] _cryptedPass = hexFromString(cryptedPass);
Security.addProvider(new BouncyCastleProvider());
IvParameterSpec _ivSpec = new IvParameterSpec(IV_BYTES);
try {
KeyGenerator _keygen = KeyGenerator.getInstance("AES");
_keygen.init(new SecureRandom(_passKey));
SecretKey _key = _keygen.generateKey();
logger.trace("Secret key generated");
Cipher _cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
_cipher.init(Cipher.DECRYPT_MODE, _key, _ivSpec);
String _pass = new String(_cipher.doFinal(_cryptedPass), "UTF-8");
logger.trace("Decrypted pass : "+_pass);
} catch (Exception e) {
logger.warn("decrypt failed");
e.printStackTrace();
}
}
private int fromDigit(char ch) {
if ((ch >= '0') && (ch <= '9')) {
return ch - '0';
} else if ((ch >= 'A') && (ch <= 'F')) {
return ch + 10 - 'A';
} else if ((ch >= 'a') && (ch <= 'f')) {
return ch + 10 - 'a';
} else {
throw new IllegalArgumentException(String.format(
"Invalid hex character 0x%04x", 0xff & ch));
}
}
private byte[] hexFromString(String hex) {
final byte[] buf = new byte[hex.length() / 2];
for (int i = 0, j = 0; i < hex.length(); i += 2) {
buf[j++] = (byte) (fromDigit(hex.charAt(i)) << 4 | fromDigit(hex
.charAt(i + 1)));
}
return buf;
}
private static String asHex(byte buf[]) {
final Formatter formatter = new Formatter(new StringBuffer());
for (int i = 0; i < buf.length; i++) {
formatter.format("%02x", 0xff & buf[i]);
}
return formatter.toString();
}
private String generateRandomKey() {
String _chars = "abcdefABCDEF1234567890";
StringBuffer _pass = new StringBuffer();
for (int x = 0; x < 32; x++) {
int i = (int) Math.floor(Math.random() * (_chars.length() - 1));
_pass.append(_chars.charAt(i));
}
return _pass.toString();
}
Does anyone knows what this exception means?
This code has a bug. It assumes that new SecureRandom(passKey.getBytes()) will initialize the SecureRandom instance with only the bytes supplied in the constructor. This is wrong. The data in the constructor will supplement whatever entropy sources SecureRandom uses, not replace them.
You need to use a proper password-based encryption (PBE) scheme.
This exception means that padding block is corrupted. You use PKCS#7 padding with 16B blocks. In this sample your output is 16B too. So it always should be added block with 16 bytes of value 0x10.
The padding is corrupted because the decryption is corrupted. Your SecureRandom implementation adds its own entropy and generates wrong decryption key. This SecureRandom constructor uses the first PRNG algorithm of the first provider that has registered a SecureRandom implementation.
I am trying to generate a key for encryption:
public static final String ENCYT_ALGORITHM = "AES/ECB/PKCS7Padding";
public static final String KEY_ALGORITHM = "PBEWITHSHA256AND256BITAES-CBC-BC" ;
//BENCYT_ALGORITHMSE64Encoder encod = new BENCYT_ALGORITHMSE64Encoder();
//BENCYT_ALGORITHMSE64Decoder decod = new BENCYT_ALGORITHMSE64Decoder();
public Encryption(String preMaster,String text,int x){
this.preMaster=preMaster;
this.text=text.getBytes();
}
public void keyGenerator(){
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance("AES");
secret = kg.generateKey();
} catch (Exception e) {
// TODO ENCYT_ALGORITHMuto-generated catch block
e.printStackTrace();
}
}
public String preMaster() {
byte[] keys = null;
keys = preMaster.getBytes();
int x = -1;
int process = 0;
while (x < keys.length - 2) {
x++;
switch (x) {
case 1:
process = keys[x + 1] | a ^ c & (d | keys[x] % a);
case 2:
process += a | (keys[x] ^ c) & d;
case 3:
process += keys[x] ^ (keys[x + 1] / a) % d ^ b;
default:
process += keys[x + 1] / (keys[x] ^ c | d);
}
}
byte[] xs = new byte[] { (byte) (process >>> 24),
(byte) (process >> 16 & 0xff), (byte) (process >> 8 & 0xff),
(byte) (process & 0xff) };
preMaster = new String(xs);
KeyGenerators key = new KeyGenerators(preMaster);
String toMaster = key.calculateSecurityHash("MD5")
+ key.calculateSecurityHash("MD2")
+ key.calculateSecurityHash("SHA-512");
return toMaster;
}
public String keyWrapper(){
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Key SharedKey = secret;
String key = null;
char[] preMaster = this.preMaster().toCharArray();
try {
byte[]salt={ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
paramSpec = new PBEParameterSpec(salt,256);
PBEKeySpec keySpec = new PBEKeySpec(preMaster,salt,1024,256);
SecretKeyFactory factory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
passwordKey = factory.generateSecret(keySpec);
Cipher c = Cipher.getInstance(KEY_ALGORITHM);
c.init(Cipher.WRAP_MODE, passwordKey, paramSpec);
byte[] wrappedKey = c.wrap(SharedKey);
key=new String(wrappedKey,"UTF8");
}catch(Exception e){
e.printStackTrace();
}
return key;
}
And this is the result :
java.security.InvalidKeyException: Illegal key size
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at fiador.authentication.util.Encryption.keyWrapper(Encryption.java:101)
at fiador.authentication.util.Encryption.main(Encryption.java:144)
null
I am really desperate ... please help me, thanks !
You have not installed the unlimited strength crypto files, (the default JDK install allows 128 bit keys as documented in http://download.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#AppC).
Download unlimited strength crypto package here.
Installation Help
I can't see where keyGenerator is being called. If it is not called, then secret is not being initialized. That could be the cause of the root exception. (It is hard to tell, because you've left out the declaration of secret.)