Block by block encryption : decryption not working from second block - java

I am implementing CBC encryption + decryption block by block by using auto generated key and self defined IV. I am getting problem in second block decryption, decryption for first block is working but its not working for second block. Here is my code.
public static void main(String args[]) {
Cipher fcipher, scipher;
String plaintextstring = "";
System.out.println("Enter the first message:");
BufferedReader buffp = new BufferedReader(new InputStreamReader(System.in));
try {
plaintextstring = buffp.readLine();
} catch (Exception e) {
System.out.println("Exception occured:" + e.getMessage());
}
int strlen1 = plaintextstring.length();
int x1 = strlen1 % 8;
int y1 = 8 - x1;
StringBuffer buf1 = new StringBuffer(plaintextstring);
if (x1 > 0) {
for (int k = 0; k < y1; k++) {
buf1.append('0');
}
}
System.out.println("Modified plaintext is:" + buf1);
String inp = buf1.toString();
try {
SecretKey key1 = KeyGenerator.getInstance("DES").generateKey();
SecretKey key2 = KeyGenerator.getInstance("DES").generateKey();
fcipher = Cipher.getInstance("DES/ECB/NoPadding");//CBC
scipher = Cipher.getInstance("DES/ECB/NoPadding");//CBC
// Create an 8-byte initialization vector
//byte[] iv = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
//byte[] iv = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
byte[] iv = {(byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08};
System.out.println("Length of IV is :" + iv.length);
byte[] sencrypted = new byte[8];
fcipher.init(Cipher.ENCRYPT_MODE, key1);
scipher.init(Cipher.DECRYPT_MODE, key2);
System.out.println("Default Charset is :" + Charset.defaultCharset());
byte[] pbytes = inp.getBytes("UTF-8");
System.out.println("Byte array of input string is :" + pbytes);
System.out.println("Size of first message in bytes is:" + pbytes.length);
for (int i = 0; i < pbytes.length; i++) {
System.out.println("Array values of byte array are: " + pbytes[i]);
}
int z = (pbytes.length) / 8;
System.out.println("Number of data blocks of 8 bytes formed from message = " + z);
for (int i = 0; i < z; i++) {
byte[] ds = getSection(pbytes, i * 8);//getting block of 64bit
byte[] out = new byte[8];
for (int r = 0; r < 8; r++) {
System.out.println("Array values of IV from previous stage is :" + iv[r]);
}
for (int k = 0; k < 8; k++) {
out[k] = (byte) (ds[k] ^ iv[k]);//XORing of message block with IV bit by bit.
// System.out.println("XORed array byte by byte is:"+out[k]);
}
byte[] fencrypted = fcipher.doFinal(out);//Applying DES Encryption to the XOR'ed result.(E)key1
byte[] fdecrypted = scipher.doFinal(fencrypted);// (D)key2
sencrypted = fcipher.doFinal(fdecrypted);// (E)key1
System.out.println("Encrypted byte length: " + sencrypted.length);
System.out.println("Encrypted text is :" + sencrypted);
fcipher.init(Cipher.DECRYPT_MODE, key1);
scipher.init(Cipher.ENCRYPT_MODE, key2);
byte[] sfdecrypted = fcipher.doFinal(sencrypted);//DES1 key1 (D)
byte[] sfencrypted = scipher.doFinal(sfdecrypted);//DES Key2 (E)
byte[] ssdecrypted = fcipher.doFinal(sfencrypted);//DES Key3 (D)
System.out.println("length of final decrypted byte array is :" + ssdecrypted.length);
byte[] d = new byte[8];
for (int u = 0; u < 8; u++) {
d[u] = (byte) (ssdecrypted[u] ^ iv[u]);//XORing of message block with IV bit by bit.
System.out.println("final decrypted array byte by byte of a single 64 bit block is:" + d[u]);
}
String sdecryptedstr = new String(d);
System.out.println("Decrypted block is :" + sdecryptedstr);
iv = sencrypted;
System.out.println("IV from previous stage is: "+iv);
}
} catch (Exception e) {
System.out.println("Exception Occured: " + e);
}
}
//function to get CBC message blocks.
public static byte[] getSection(byte[] message, int start) {
byte[] section = new byte[8];//dividing whole message into 64bit blocks.
for (int i = 0, j = start; i < 8; i++, j++) {
section[i] = message[j];
}
return section;
}//end of getSection function.

Related

Aes encrypt in Java and decrypt in C#

In Java code, i have source work well, this is use for encrypt:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class HelloWorld{
private static final String hexKey = "B8EE12E123C0E300A202074A153CC0D27D739357480FFFFFFFFFFFFFFFFFFFEF";
public static void main(String []args){
System.out.println("Encryt ==== ");
String textToEncrypt = "From=ABC&Key=FootID1234&Value=ResultValue2324";
String encryptedText = encrypt(textToEncrypt);
System.out.println(encryptedText);
System.out.println("Decrypt ==== ");
String decryptedText = decrypt(encryptedText);
System.out.println(decryptedText);
}
public static String encrypt (String plainText) {
String encryptedText = null;
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
SecretKeySpec secretKey = new SecretKeySpec(hexToBytes(hexKey), "AES");
IvParameterSpec ivparameterspec = new IvParameterSpec(hexKey.getBytes(), 0, 16);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivparameterspec);
byte[] cipherText = cipher.doFinal(plainText.getBytes("UTF8"));
encryptedText = bytesToHex(cipherText);
} catch (Exception E) {
System.out.println("Encrypt Exception : " + E.getMessage());
}
return encryptedText;
}
public static String decrypt(String encryptedText) {
String decryptedText = null;
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
SecretKeySpec secretKey = new SecretKeySpec(hexToBytes(hexKey), "AES");
IvParameterSpec ivparameterspec = new IvParameterSpec(hexKey.getBytes("UTF8"), 0, 16);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivparameterspec);
byte[] cipherText = hexToBytes(encryptedText);
byte[] dcrbyte = cipher.doFinal(cipherText);
decryptedText = new String(dcrbyte, "UTF-8");
} catch (Exception E) {
System.out.println("Encrypt Exception : " + E.getMessage());
}
return decryptedText;
}
private static byte[] hexToBytes(String hexStr) {
byte[] val = new byte[hexStr.length() / 2];
for (int i = 0; i < val.length; i++) {
int idx = i * 2;
int j = Integer.parseInt(hexStr.substring(idx, idx + 2), 16);
val[i] = (byte) j;
}
return val;
}
private static String bytesToHex(byte[] hashInBytes) {
char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[hashInBytes.length * 2];
for (int i = 0; i < hashInBytes.length; i++) {
int v = hashInBytes[i] & 0xFF;
hexChars[i * 2] = hexArray[v >>> 4];
hexChars[i * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
And in c#, i try to write decryptAes() function like this:
public static class Encryption
{
// use these parameters to test decryptAes()
//string key = "B8EE12E123C0E300A202074A153CC0D27D739357480FFFFFFFFFFFFFFFFFFFEF";
//string textToDecrypt = "756AD4D80E2CF1E289D55A23E092F012E8D5F372A343A419BC87F77B6335F04EFB41C3B56F5CDA167F90F67CD672A186";
public static string decryptAes(string key, string textToDecrypt)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
// Assumed Mode and padding values.
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
// AssumedKeySize and BlockSize values.
rijndaelCipher.KeySize = 0x80; //128
rijndaelCipher.BlockSize = 0x80;
// Convert Hex keys to byte Array.
byte[] encryptedData = HexToBytes(textToDecrypt);
//byte[] pwdBytes = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(key);
byte[] pwdBytes = HexToBytes(key);
byte[] keyBytes = new byte[0x10]; //16
int len = pwdBytes.Length;
if (len > keyBytes.Length)
{
len = keyBytes.Length;
}
Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
// Decrypt data
byte[] plainText = rijndaelCipher.CreateDecryptor()
.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(plainText);
}
public static byte[] HexToBytes(string str)
{
if (str.Length == 0 || str.Length % 2 != 0)
return new byte[0];
byte[] buffer = new byte[str.Length / 2];
char c;
for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)
{
// Convert first half of byte
c = str[sx];
buffer[bx] = (byte)((c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0')) << 4);
// Convert second half of byte
c = str[++sx];
buffer[bx] |= (byte)(c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0'));
}
return buffer;
}
public static string ByteToHex(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString().ToUpper();
}
}
But the c# decryptAes() function does not work as i expect. An error
System.Security.Cryptography.CryptographicException: 'Padding is invalid and cannot be removed.'
has occured at line rijndaelCipher.Padding = PaddingMode.PKCS7;
When i change to rijndaelCipher.Padding = PaddingMode.None, it does not work as i expect, the c# result is not the same as the result of java.
Please help, any advice would be appreciated!
Thanks!
You need to explicitly set the padding for both encryption and decryption. Unless you have a reason to do otherwise, use PKCS#7 padding.
rijndaelCipher.Padding=PaddingMode.none;

Java equivalent for php AES encryption

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);
}

Crypting Error in java with signed bytes

I'm trying to create a pair of function in java that has to crypts(first one funct.) a message give as an array of bytes and decrypt it(second one), by working with bytes and a simple crypting algorithm that simply functions by picking up a random byte that will be the key, adding the key to the single bytes of the messagge and append it at the end of the message. It even uses a list of prohibited byte that can't be used as key, and that's it. The problem is that i don't know why it functiones only when the key is negative(Ex: With 47 as key it doesn't decrypt correctly the message, but with -68 as the key it works).
Thanks.
public byte[] prohib = {33, 4, 15};
public byte[] Crypt(byte[] messTo) throws NoSuchAlgorithmException {
if (messTo.length <= 2) {
return messTo;
} else {
byte[] crypted = new byte[messTo.length + 1];
byte[] key_arr = new byte[1];
new Random().nextBytes(key_arr);
byte key = key_arr[0];
while (ifProhib(key)) {
System.out.println("Prohib key: " + key);
new Random().nextBytes(key_arr);
key = key_arr[0];
}
System.out.println("CryptedKey == " + key);
for (int i = 0; i < messTo.length; i++) {
if ((crypted[i] = (byte) (messTo[i] + key)) > 127) {
crypted[i] = (byte) (messTo[i] + key - 255);
} else {
crypted[i] = (byte) (messTo[i] + key);
}
crypted[crypted.length - 1] = key;
}
return crypted;
}
}
public byte[] Decrypt(byte[] in) {
if (in.length <= 2) {
return in;
} else {
byte key = in[in.length - 1];
byte[] decrypted = new byte[in.length - 1];
System.out.println("DecryptedKey == " + key);
for (int i = 0; i < decrypted.length; i++) {
if (in[i] - key < -128) {
decrypted[i] = (byte) (in[i] - key + 255);
} else {
decrypted[i] = (byte) (in[i] - key);
}
}
return decrypted; //decrypted
}
}
public boolean ifProhib(byte key) {
for (int m = 0; m < prohib.length; m++) {
if (key == prohib[m]) {
return true;
}
}
return false;
}

Getting a padding exception in javax.crypto

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.

Java AES 256 Secure Key Generator -- Illegal key size

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.)

Categories