Issue in sending encoded parameters on servlet - java

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

Related

AES encryption .Net to Android for mobile

I referred to the below link
AES Encryption .net to swift,
But, applying the same for ANDROID, I am not able to get the correct AES encryption with version(PBKDF2) conversion for my code. NEED HELP.
public static String Encrypt(String PlainText) throws Exception {
try {
byte[] salt = new byte[] { 0x49, 0x76, 0x61, 0x6E, 0x20, 0x4D,
0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 };
System.out.println("Exception setting up cipher: "+pbkdf2("<keyname>",salt.toString(),1024,128));
Cipher _aesCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
byte[] keyBytes =pbkdf2("<keyname>",salt.toString(),1024,128).getBytes();
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
byte[] iv ="OFRna73m*aze01xY".getBytes();//pbkdf2("<keyname>",salt.toString(),2,64).getBytes();
IvParameterSpec ivSpec = new IvParameterSpec(iv);
_aesCipher.init(1, keySpec, ivSpec);
byte[] plainText = PlainText.getBytes();
byte[] result = _aesCipher.doFinal(plainText);
return Base64.encodeToString(result, Base64.DEFAULT);//Base64.encode(result,1));
} catch (Exception ex1) {
System.out.println("Exception setting up cipher: "
+ ex1.getMessage() + "\r\n");
ex1.printStackTrace();
return "";
}
}
public static String pbkdf2(String password, String salt, int iterations, int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException {
char[] chars = password.toCharArray();
PBEKeySpec spec = new PBEKeySpec(chars, salt.getBytes(), iterations, keyLength);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] hash = skf.generateSecret(spec).getEncoded();
return toHex(hash);
}
// Converts byte array to a hexadecimal string
private static String toHex(byte[] array) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; i++) {
sb.append(Integer.toString((array[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
Please check below code .
I have created Singletone class for the same so that i can access it anywhere in app.
Below Points Should be same like .net or swift
Important Points are IV , SALT and PASSWORD
Please check this too PBKDF2WithHmacSHA1
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
to generate key we used this
KeySpec spec = new PBEKeySpec(password, salt, 2, 256);
Importnant points are (password, salt,iterantion,bytes) this must be same like other platform which you are using with like .net or swift
public class AesBase64Wrapper {
private static String IV = "it should be same like server or other platform";
private static String PASSWORD = "it should be same like server or other platform";
private static String SALT = "it should be same like server or other platform";
private static volatile AesBase64Wrapper sSoleInstance = new AesBase64Wrapper();
//private constructor.
private AesBase64Wrapper() {
}
public static AesBase64Wrapper getInstance() {
return sSoleInstance;
}
// For Encryption
public String encryptAndEncode(String raw) {
try {
Cipher c = getCipher(Cipher.ENCRYPT_MODE);
byte[] encryptedVal = c.doFinal(getBytes(raw));
//String retVal = Base64.encodeToString(encryptedVal, Base64.DEFAULT);
String retVal = Base64.encodeToString(encryptedVal, Base64.NO_WRAP);
return retVal;
}catch (Throwable t) {
throw new RuntimeException(t);
}
}
public String decodeAndDecrypt(String encrypted) throws Exception {
// byte[] decodedValue = Base64.decode(getBytes(encrypted),Base64.DEFAULT);
byte[] decodedValue = Base64.decode(getBytes(encrypted), Base64.NO_WRAP);
Cipher c = getCipher(Cipher.DECRYPT_MODE);
byte[] decValue = c.doFinal(decodedValue);
return new String(decValue);
}
private String getString(byte[] bytes) throws UnsupportedEncodingException {
return new String(bytes, "UTF-8");
}
private byte[] getBytes(String str) throws UnsupportedEncodingException {
return str.getBytes("UTF-8");
}
private Cipher getCipher(int mode) throws Exception {
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = getBytes(IV);
String xyz = String.valueOf(generateKey());
Log.i("generateKey", xyz);
c.init(mode, generateKey(), new IvParameterSpec(iv));
return c;
}
private Key generateKey() throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
char[] password = PASSWORD.toCharArray();
byte[] salt = getBytes(SALT);
KeySpec spec = new PBEKeySpec(password, salt, 2, 256);
SecretKey tmp = factory.generateSecret(spec);
byte[] encoded = tmp.getEncoded();
byte b = encoded[1];
Log.e("Secrete Key", String.valueOf(encoded));
return new SecretKeySpec(encoded, "CBC");
}
}
In Activity you can use it like
String EncryptString = AesBase64Wrapper.getInstance().encryptAndEncode("hello");
String DecryptString = AesBase64Wrapper.getInstance().encryptAndEncode(EncryptString);
// You will Get Output in Decrypted String

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

Having trouble porting this from vb.net to Java AES encryption

Here is the full working example of something encoded in .net and decoded in Java and vice-versa
Private Function Decrypt(cipherText As String) As String
dim _encryptionkey as string = "kmjfds(#1231SDSA()#rt32geswfkjFJDSKFJDSFd"
Dim cipherBytes As Byte() = Convert.FromBase64String(cipherText)
Using encryptor As Aes = Aes.Create()
Dim pdb As New Rfc2898DeriveBytes(_EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, &H65, &H64, &H76, &H65, &H64, &H65, _
&H76})
encryptor.Key = pdb.GetBytes(32)
encryptor.IV = pdb.GetBytes(16)
Using ms As New MemoryStream()
Using cs As New CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)
cs.Write(cipherBytes, 0, cipherBytes.Length)
cs.Close()
End Using
cipherText = Encoding.Unicode.GetString(ms.ToArray())
End Using
End Using
Return cipherText
End Function
Here is the Java equivalent. Thanks for everyone's help! Make sure to install the JCE policy in the security folder of your Java as well.
String myData = "kgxCSfBSw5BRxmjgc4qYhwN12dxG0dyf=";
byte[] salt = new byte[] {0x49, 0x76, 0x61, 0x6E, 0x20, 0x4D, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76};
String pw = "kmjfds(#1231SDSA()#rt32geswfkjFJDSKFJDSFd";
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec pbeKeySpec = new PBEKeySpec(pw.toCharArray(), salt, 1000, 384);
Key secretKey = factory.generateSecret(pbeKeySpec);
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 secretSpec = new SecretKeySpec(key, "AES");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Cipher cipher1 = Cipher.getInstance("AES/CBC/PKCS5Padding");
try {
cipher.init(Cipher.DECRYPT_MODE,secretSpec,ivSpec);
cipher1.init(Cipher.ENCRYPT_MODE,secretSpec,ivSpec);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//byte[] decordedValue;
//decordedValue = new BASE64Decoder().decodeBuffer(myData);
//decordedValue = myData.getBytes("ISO-8859-1");
//byte[] decValue = cipher.doFinal(myData.getBytes());
//Base64.getMimeEncoder().encodeToString(cipher.doFinal(myData.getBytes()));
//String decryptedValue = new String(decValue);
byte[] decodedValue = new Base64().decode(myData.getBytes());
String clearText = "ljfva09876FK";
//String encodedValue = new Base64().encodeAsString(clearText.getBytes("UTF-16"));
byte[] cipherBytes = cipher1.doFinal(clearText.getBytes("UTF-16LE"));
//String cipherText = new String(cipherBytes, "UTF8");
String encoded = Base64.encodeBase64String(cipherBytes);
System.out.println(encoded);
byte[] decValue = cipher.doFinal(decodedValue);
System.out.println(new String(decValue, StandardCharsets.UTF_16LE));
Your iteration count should be 1000 (instead of 1), which is the recommended minimum in the RFC and the (unspecified) default of Rfc2898DeriveBytes.
For the methods in this document, a minimum
of 1000 iterations is recommended
So that would translate into:
PBEKeySpec pbeKeySpec = new PBEKeySpec(pw.toCharArray(), salt, 1000, 384);
within the Java code. Note that a higher iteration count is highly recommended, especially if weaker passwords are allowed. 40K-100K is about the minimum now.
The incorrectly named Unicode actually means UTF-16 in .NET, so you should use:
new String(decValue, StandardCharsets.UTF_16LE)
within the last println statement of the Java code.
Here is the answer thanks to Maarten Bodewes
String myData = "kgxCSfBSw5BRxmjgc4qYhwN12dxG0=";
byte[] salt = new byte[] {0x49, 0x76, 0x61, 0x6E, 0x20, 0x4D, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76};
String pw = "kmjfds(#1231SDSA()#rt32geswfkjFJDSKFJDSFd";
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec pbeKeySpec = new PBEKeySpec(pw.toCharArray(), salt, 1000, 384);
Key secretKey = factory.generateSecret(pbeKeySpec);
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 secretSpec = new SecretKeySpec(key, "AES");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
try {
cipher.init(Cipher.DECRYPT_MODE,secretSpec,ivSpec);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//byte[] decordedValue;
//decordedValue = new BASE64Decoder().decodeBuffer(myData);
//decordedValue = myData.getBytes("ISO-8859-1");
//byte[] decValue = cipher.doFinal(myData.getBytes());
//Base64.getMimeEncoder().encodeToString(cipher.doFinal(myData.getBytes()));
//String decryptedValue = new String(decValue);
byte[] decodedValue = new Base64().decode(myData.getBytes());
byte[] decValue = cipher.doFinal(decodedValue);
System.out.println(new String(decValue, StandardCharsets.UTF_16LE));

emulate pbewithmd5anddes in javascript

I made a password generating program some time ago in java.
it generated passwords based on an input string and password.
it used: pbewithMD5andDES
now i'm making a new version of this for mobile devices in javascript.
i found the library crypto-js witch allows me to generate MD5-hashes and encrypt using DES
but i can't seem to generate identical passwords
what am i doing wrong?
java version:
public static String generate(String password, String passphase) throws Exception {
try {
PBEKeySpec pbeKeySpec = new PBEKeySpec(passphase.toCharArray());
PBEParameterSpec pbeParamSpec;
SecretKeyFactory keyFac;
// Salt
byte[] salt = {(byte) 0xc8, (byte) 0x73, (byte) 0x61, (byte) 0x1d, (byte) 0x1a, (byte) 0xf2, (byte) 0xa8, (byte) 0x99};
// Iteration count
int count = 20;
// Create PBE parameter set
pbeParamSpec = new PBEParameterSpec(salt, count);
keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
// Create PBE Cipher
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
// Initialize PBE Cipher with key and parameters
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
// Our cleartext
byte[] cleartext = password.getBytes();
// Encrypt the cleartext
byte[] ciphertext = pbeCipher.doFinal(cleartext);
return byteArrayToHexString(ciphertext).substring(0, 12);
} catch (Exception ex) {
throw new Exception(ex.getMessage());
}
}
public static String byteArrayToHexString(byte[] b){
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++){
int v = b[i] & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
}
the new javascript version (not compete): (i tried both orders: first hashing then DES, and the oher way around)
var hashedPassword = CryptoJS.MD5(password);
var encryptedPassword = CryptoJS.DES.encrypt(hashedPassword, passphrase).toString();
var result = encryptedPassword.toString().substring(0, 12).toUpperCase();
am i on the right way?

BOUNCY CAStLE AES 256 decryption problem in java

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.

Categories