I have a project where our provider has their own DES Encryption logic however I am using django as my backend. I can run the java using subprocess but I'm actually planning to convert that java code to python..
Here is my code:
import java.io.*;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
public class PHPDESEncrypt {
String key;
public PHPDESEncrypt() {
}
public PHPDESEncrypt(String key) {
this.key = key;
}
public byte[] desEncrypt(byte[] plainText) throws Exception {
SecureRandom sr = new SecureRandom();
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key, sr);
byte data[] = plainText;
byte encryptedData[] = cipher.doFinal(data);
return encryptedData;
}
public String encrypt(String input) throws Exception {
return base64Encode(desEncrypt(input.getBytes())).replaceAll("\\s*", "");
}
public String base64Encode(byte[] s) {
if (s == null) return null;
BASE64Encoder b = new BASE64Encoder();
return b.encode(s);
}
public static void main(String args[]) {
try {
PHPDESEncrypt d = new PHPDESEncrypt(args[0]);
String p=d.encrypt(args[1]);
System.out.println(p);
}
catch (Exception e) {
e.printStackTrace();
}
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
Any suggestions on how to convert this? Like a library or an online tool? Or it would be better if there is someone good enough who can easily convert this
I run it in java like:
java PHPDESEncrypt "3r108w5A" "cagent=sample/\\\\/loginname=sample/\\\\/password=password/\\\\/method=ca/\\\\/actype=0/\\\\/cur=USD"
The result should be:
lt5tEqnzRCx67vJ8j3Ap5zIVZYkT01Ho+irM1NPdReJqwyrP9vlypDXvExx9sCOEJPcPCET0aPpKFkW1punRxP/uD8IFM1j4umwLuJpxPQTOdwJsbuuRmhmkFml6l3OV
use pyDes with python3, here is the demo code:
def des_ecb_encode(source, key):
des_obj = des(key, ECB, IV=None, pad=None, padmode=PAD_PKCS5)
des_result = des_obj.encrypt(source)
return base64.encodestring(des_result)
if __name__ == '__main__':
src = b'cagent=81288128/\\\\/method=tc'
key = b'12341234'
encrypted = des_ecb_encode(src, key)
print('encrypted: ', encrypted)
and it will print
encrypted: b'IGcOAYEQN88F1NFLtBOK23PMeg42F7r8jchYOmglMAs=\n'
I already answered it using pycrypto here's the code
from Crypto.Cipher import DES
from base64 import b64encode
def pad(s):
return s + (DES.block_size - len(s) % DES.block_size) * \
chr(DES.block_size - len(s) % DES.block_size)
def get_params(data):
params = ''
if not data:
return params
for key, value in data.iteritems():
if key and value:
params += '{0}={1}/\\\/'.format(key, value)
return params[:-4]
def des_encrypt(plain_text):
key = '3r108w5A'
des = DES.new(key)
return b64encode(des.encrypt(pad(plain_text)))
create_params = {'cagent': 'sample',
'loginname': 'sample',
'password': 'password',
'method': 'ca',
'actype': '0',
'cur': 'USD'}
params = des_encrypt(get_params(create_params))
Related
I have written encrypt and decrypt methods to encrypt or decrypt string data. We have some vulnerability analyzer tool that says "javas.crypto.spec.SecretKeySpec.SecretKeySpec(byte[], java.lang.String) uses the constant string as a cryptographic key" at this line:
return new SecretKeySpec(decoded, keyAlgorithm);
I tried giving "AES" directly instead of variable/field, still it gave the same error. Can you please help me on what changes need to be done in this code so that the errors won't appear and make this implementation more secure?
Here is the complete code for it:
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;
public class EncryptDecryptImpl {
private static final String secretKey = "abcdefghijklmnop";
private static final String otherSecretKey = "somesecret";
private static final String encryptionAlgorithm = "AES/CBC/PKCS5Padding";
private static final String keyAlgorithm = "AES";
public static String encrypt(String data, String secret) {
try {
Key key = generateKey(secret);
Cipher cipher = Cipher.getInstance(encryptionAlgorithm);
SecureRandom secureRandom = new SecureRandom();
byte[] iv = new byte[16];
secureRandom.nextBytes(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
byte[] ciphertext = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
byte[] encryptedValue = ByteBuffer.allocate(iv.length + ciphertext.length)
.put(iv).put(ciphertext).array();
return Base64.getEncoder().encodeToString(encryptedValue);
} catch (InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException |
BadPaddingException | IllegalBlockSizeException | InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(String strToDecrypt, String secret) {
try {
Key key = generateKey(secret);
Cipher cipher = Cipher.getInstance(encryptionAlgorithm);
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException |
BadPaddingException | IllegalBlockSizeException e) {
e.printStackTrace();
}
return null;
}
private static Key generateKey(String secret) {
byte[] decoded = Base64.getDecoder().decode(secret.getBytes());
return new SecretKeySpec(decoded, keyAlgorithm);
}
public static String encodeKey(String key) {
byte[] encoded = Base64.getEncoder().encode(key.getBytes());
return new String(encoded);
}
public static String decodeKey(String key) {
byte[] decoded = Base64.getDecoder().decode(key.getBytes());
return new String(decoded);
}
public static String encodedBase64Key() {
return encodeKey(secretKey); // need to be shared between client and server
}
public static String decodedBase64Key(String encryptedSecretKey) {
return decodeKey(encryptedSecretKey);
}
public static String aesEncryptedSecretKey() {
return EncryptDecryptImpl.encrypt(otherSecretKey, encodedBase64Key());
}
public static String aesDecryptedSecretKey() {
return EncryptDecryptImpl.decrypt(aesEncryptedSecretKey(), encodedBase64Key());
}
}
Caller:
#RestController
#RequestMapping("/service/crypto")
public class EncryptDecryptController {
#GetMapping(value = "/secret-key")
public ResponseEntity<?> getEncryptedSecretKey() {
try {
String encryptedSecretKey = EncryptDecryptImpl.aesEncryptedSecretKey(); // cipher text
return ResponseEntity.ok(new ApiResponse(true, encryptedSecretKey));
} catch (Exception e) {
return ResponseEntity.ok(new ApiResponse(false, "Error getting key"));
// throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Error getting key", e);
}
}
}
And at the client side, I'm using like this:
export const getSecretKey = () => {
const encryptedBase64Key = '<--base64kyesharedbyserver-->';
const parsedBase64Key = enc.Base64.parse(encryptedBase64Key);
let encryptedCipherText = '';
if (getSessionStorageItem('appKey') !== null) {
encryptedCipherText = getSessionStorageItem('appKey');
}
const parsedCipherText = enc.Base64.parse(encryptedCipherText);
const iv = lib.WordArray.create(parsedCipherText.words.slice(0, 16 / 4));
const ciphertext = lib.WordArray.create(parsedCipherText.words.slice(16 / 4));
let decryptedData = '';
if (encryptedCipherText !== '' || encryptedCipherText !== undefined) {
decryptedData = AES.decrypt({
ciphertext: ciphertext
}, parsedBase64Key,{
iv: iv
});
}
return decryptedData.toString(enc.Utf8).toString();
}
export const encryptData = (data) => {
return AES.encrypt(data, getSecretKey());
}
export const decryptData = (data) => {
if (data !== undefined) {
return AES.decrypt(data, getSecretKey()).toString(enc.Utf8);
} else {
return '';
}
}
We are developing the ionc v3 based mobile app and we have to encrypt the password at front side and needs to decrypt the password at java middleware level. now ionic v3 we did sample encryption but the encrypted data not able to decrypt in our java. please advise as below ionic and java code, where we have to change it exactly.
ionic v3 AES 256 sample code
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { AES256 } from '#ionic-native/aes-256';
import { Platform } from 'ionic-angular/index';
import * as CryptoJS from 'crypto-js';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
text: string;
private secureKey:string ;// Any string, the length should be 32
private secureIV:string ;
private password = "test#123"
EncryptedData :string;
constructor(public navCtrl: NavController, private aes256: AES256, private platform: Platform) {
this.generateSecureKey(this.password);
this.generateSecureIV(this.password);
}
generateSecureKey(password) {
this.platform.ready().then(() => {
this.aes256.generateSecureKey(password).then((secureKey) => {
this.secureKey = secureKey;
console.log('Secure Key----', secureKey);
}, (error) => {
console.log('Error----', error);
});
});
}
generateSecureIV(password) {
this.platform.ready().then(() => {
this.aes256.generateSecureIV(password).then((secureIV) => {
this.secureIV = secureIV;
console.log('Secure Key----', secureIV);
}, (error) => {
console.log('Error----', error);
});
});
}
encrypt() {
this.platform.ready().then(() => {
this.aes256.encrypt(this.secureKey, this.secureIV, this.text)
.then(res => {alert('Encrypted Data: '+res)
console.log("Secure Key" +this.secureKey);
console.log("Secure Key" +this.secureIV);
this.EncryptedData = res;
console.log(EncryptedData);
})
.catch((error: any) => console.error(error));
});
}
decrypt() {
this.platform.ready().then(() => {
this.aes256.decrypt(this.secureKey, this.secureIV, this.EncryptedData)
.then(res => { alert('Decrypted Data : '+res)
console.log("Secure Key" +this.secureKey);
console.log("Secure Key" +this.secureIV);
})
.catch((error: any) => console.error(error));
});
}
}
Java Code sample:
package com.test.reactapi;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class TestEncry {
private static final String ENCRYPT_ALGO = "AES/GCM/NoPadding";
private static final int TAG_LENGTH_BIT = 128;
private static final Charset UTF_8 = StandardCharsets.UTF_8;
public static String encrypt(byte[] pText) throws Exception {
String password = "test#123";
byte[] salt = getRandomNonce(32);
byte[] iv = getRandomNonce(12);
SecretKey aesKeyFromPassword = getAESKeyFromPassword(password.toCharArray(), salt);
Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);
cipher.init(1, aesKeyFromPassword, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
byte[] cipherText = cipher.doFinal(pText);
byte[] cipherTextWithIvSalt = ByteBuffer.allocate(iv.length + salt.length + cipherText.length).put(iv).put(salt)
.put(cipherText).array();
return Base64.getEncoder().encodeToString(cipherTextWithIvSalt);
}
public static SecretKey getAESKeyFromPassword(char[] password, byte[] salt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("SHA256");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
}
public static String decrypt(String cText) throws Exception {
byte[] plainText = null;
try {
String password = "test#123";
byte[] decode = Base64.getDecoder().decode(cText.getBytes(UTF_8));
ByteBuffer bb = ByteBuffer.wrap(decode);
byte[] iv = new byte[12];
bb.get(iv);
byte[] salt = new byte[32];
bb.get(salt);
byte[] cipherText = new byte[bb.remaining()];
bb.get(cipherText);
SecretKey aesKeyFromPassword = getAESKeyFromPassword(password.toCharArray(), salt);
Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);
cipher.init(2, aesKeyFromPassword, new GCMParameterSpec(128, iv));
plainText = cipher.doFinal(cipherText);
} catch (Exception e) {
e.printStackTrace();
}
return new String(plainText, UTF_8);
}
public static byte[] getRandomNonce(int numBytes) {
byte[] nonce = new byte[numBytes];
new SecureRandom().nextBytes(nonce);
return nonce;
}
public static void main(String[] args) throws Exception {
System.out.println("Decrypted pwd:" + decrypt("kkkkkk/kllmnn=="));
}
}
please advise and help us
error :
java.nio.BufferUnderflowException
at java.nio.HeapByteBuffer.get(HeapByteBuffer.java:151)
at java.nio.ByteBuffer.get(ByteBuffer.java:715)
at com.test.reactapi.TestEncry.decrypt(TestEncry.java:62)
at com.test.reactapi.TestEncry.main(TestEncry.java:90)
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.<init>(String.java:515)
at com.test.reactapi.TestEncry.decrypt(TestEncry.java:73)
at com.test.reactapi.TestEncry.main(TestEncry.java:90)
So usually i use one java file to encrypt and decrypt a string to hex with AES,
then my angular app want to consume api, that use the result of it.
this is my old java code
package decryptoor;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Formatter;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class CryptoAndroidKoplak {
private static final String TEXT_ENCODING = "UTF-8";
private static final String CIPHER_TRANSFORMATION = "AES/CBC/PKCS5Padding";
private static final String ENCRYPTION_ALGORITM = "AES";
private static final String TAG = "Crypto";
private Cipher cipher;
private IvParameterSpec initialVector;
// private static void DEBUG(String msg){
// if(IDefines.DEBUG_LOG_TRACE){
// Log.i(TAG, msg);
// }
// }
public CryptoAndroidKoplak() {
try {
cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
initialVector = new IvParameterSpec(new byte[16]);
} catch (Exception e) {
System.out.println(e.toString());
}
}
public String encryptString(String plainText, String key) throws Exception {
return toHexString(encrypt(plainText, key)).toUpperCase();
}
public byte[] encrypt(String plainText, String key) throws Exception {
byte[] byteKey = getKeyBytes(key);
byte[] plainData = plainText.getBytes(TEXT_ENCODING);
SecretKeySpec keySpec = new SecretKeySpec(byteKey, ENCRYPTION_ALGORITM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, initialVector);
return cipher.doFinal(plainData);
}
public String decryptString(String encryptedText, String key) throws Exception {
return new String(decrypt(encryptedText, key));
}
public byte[] decrypt(String encryptedText, String key) throws Exception {
byte[] byteKey = getKeyBytes(key);
byte[] encryptData = hexToAscii(encryptedText);
SecretKeySpec keySpec = new SecretKeySpec(byteKey, ENCRYPTION_ALGORITM);
cipher.init(Cipher.DECRYPT_MODE, keySpec, initialVector);
return cipher.doFinal(encryptData);
}
public static String toMD5(String text) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] data = text.getBytes(TEXT_ENCODING);
return toHexString(md.digest(data));
}
public static String toSHA1(String text) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] data = text.getBytes(TEXT_ENCODING);
return toHexString(md.digest(data));
}
private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
Formatter formatter = new Formatter(sb);
for (byte b : bytes) {
formatter.format("%02x", b);
}
return sb.toString();
}
private static byte[] hexToAscii(String hexStr) {
byte[] buff = new byte[hexStr.length() / 2];
int offset = 0;
for (int i = 0; i < hexStr.length(); i += 2) {
String str = hexStr.substring(i, i + 2);
buff[offset++] = (byte) Integer.parseInt(str, 16);
}
return buff;
}
private static byte[] getKeyBytes(String key) throws UnsupportedEncodingException {
byte[] keyBytes = new byte[16];
byte[] parameterKeyBytes = key.getBytes("UTF-8");
System.arraycopy(parameterKeyBytes, 0, keyBytes, 0, Math.min(parameterKeyBytes.length, keyBytes.length));
return keyBytes;
}
}
and this is my code in angular
import { Injectable } from '#angular/core';
import * as CryptoJS from 'crypto-js';
#Injectable({
providedIn: 'root'
})
export class Encryption {
constructor() {}
encryptAesToString(stringToEncrypt: string, key: string): string {
// first way
// let encrypted;
// try {
// encrypted = CryptoJS.AES.encrypt(JSON.stringify(stringToEncrypt), key);
// } catch (e) {
// console.log(e);
// }
// encrypted = CryptoJS.enc.Hex.stringify(encrypted.ciphertext);
// return encrypted;
// second way
// var b64 = CryptoJS.AES.encrypt(stringToEncrypt, key).toString();
// var e64 = CryptoJS.enc.Base64.parse(b64);
// var eHex = e64.toString(CryptoJS.enc.Hex);
// return eHex;
// third way
const key2 = CryptoJS.enc.Utf8.parse(key);
const iv = CryptoJS.enc.Utf8.parse(key);
const encrypted = CryptoJS.AES.encrypt(stringToEncrypt, key2, {
keySize: 16,
iv: iv,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
let eHex = CryptoJS.enc.Hex.stringify(encrypted.ciphertext);
return encrypted;
}
decryptAesformString(stringToDecrypt: string, key: string): string {
let decrypted: string = '';
try {
const bytes = CryptoJS.AES.decrypt(stringToDecrypt, key);
if (bytes.toString()) {
decrypted = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
}
} catch (e) {
console.log(e);
}
return decrypted;
}
}
i have try three code, the first one doesn't return hex, so i try 2 more ways but it doesn't show same encrypted string with the old java code so i cant consume the api.
any idea why this happen?
if you have better way to encrypt and decrypt with key that more simple both in angular and java, it will really help.
many thanks
after give up on how to make it same with my old java code, finally i try to make a new one hehe...
so after i read this answer, then i understand CryptoJS (library that i use in angular) implements the same key derivation function as OpenSSL. so i choose to use basic CryptoJS function to encrypt my string like this
var text = "The quick brown fox jumps over the lazy dog. 👻 👻";
var secret = "René Über";
var encrypted = CryptoJS.AES.encrypt(text, secret);
encrypted = encrypted.toString();
console.log("Cipher text: " + encrypted);
after that, what i need to do is make new java file to encrypt and decrypt aes OpenSsl, and i get what i need here in this answer. i use robert answer, cause accepted answer not really give me what i need.
but like the first answer mentioned, to encrypt and decrypt in this way, we have to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy. Otherwise, AES with key size of 256 won't work and throw an exception:(you won't need JCE with up-to-date java version)
so i add some functionality to force using AES with key size of 256 without to install JCE here. note to use this, actually isnt recomended, please read the comment in ericson answer
then this is my final code to encrypt and decrypt like OpenSsl
package decryptoor;
import groovy.transform.CompileStatic;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.SecureRandom;
import static java.nio.charset.StandardCharsets.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.Arrays;
import java.util.Base64;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
/**
* Mimics the OpenSSL AES Cipher options for encrypting and decrypting messages using a shared key (aka password) with symetric ciphers.
*/
#CompileStatic
class OpenSslAes {
/** OpenSSL's magic initial bytes. */
private static final String SALTED_STR = "Salted__";
private static final byte[] SALTED_MAGIC = SALTED_STR.getBytes(US_ASCII);
static String encryptAndURLEncode(String password, String clearText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, InvalidAlgorithmParameterException, BadPaddingException, UnsupportedEncodingException {
String encrypted = encrypt(password, clearText);
return URLEncoder.encode(encrypted, UTF_8.name() );
}
/**
*
* #param password The password / key to encrypt with.
* #param data The data to encrypt
* #return A base64 encoded string containing the encrypted data.
*/
static String encrypt(String password, String clearText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, InvalidAlgorithmParameterException, BadPaddingException {
removeCryptographyRestrictions();
final byte[] pass = password.getBytes(US_ASCII);
final byte[] salt = (new SecureRandom()).generateSeed(8);
final byte[] inBytes = clearText.getBytes(UTF_8);
final byte[] passAndSalt = array_concat(pass, salt);
byte[] hash = new byte[0];
byte[] keyAndIv = new byte[0];
for (int i = 0; i < 3 && keyAndIv.length < 48; i++) {
final byte[] hashData = array_concat(hash, passAndSalt);
final MessageDigest md = MessageDigest.getInstance("MD5");
hash = md.digest(hashData);
keyAndIv = array_concat(keyAndIv, hash);
}
final byte[] keyValue = Arrays.copyOfRange(keyAndIv, 0, 32);
final byte[] iv = Arrays.copyOfRange(keyAndIv, 32, 48);
final SecretKeySpec key = new SecretKeySpec(keyValue, "AES");
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
byte[] data = cipher.doFinal(inBytes);
data = array_concat(array_concat(SALTED_MAGIC, salt), data);
return Base64.getEncoder().encodeToString( data );
}
/**
* #see http://stackoverflow.com/questions/32508961/java-equivalent-of-an-openssl-aes-cbc-encryption for what looks like a useful answer. The not-yet-commons-ssl also has an implementation
* #param password
* #param source The encrypted data
* #return
*/
static String decrypt(String password, String source) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
removeCryptographyRestrictions();
final byte[] pass = password.getBytes(US_ASCII);
final byte[] inBytes = Base64.getDecoder().decode(source);
final byte[] shouldBeMagic = Arrays.copyOfRange(inBytes, 0, SALTED_MAGIC.length);
if (!Arrays.equals(shouldBeMagic, SALTED_MAGIC)) {
throw new IllegalArgumentException("Initial bytes from input do not match OpenSSL SALTED_MAGIC salt value.");
}
final byte[] salt = Arrays.copyOfRange(inBytes, SALTED_MAGIC.length, SALTED_MAGIC.length + 8);
final byte[] passAndSalt = array_concat(pass, salt);
byte[] hash = new byte[0];
byte[] keyAndIv = new byte[0];
for (int i = 0; i < 3 && keyAndIv.length < 48; i++) {
final byte[] hashData = array_concat(hash, passAndSalt);
final MessageDigest md = MessageDigest.getInstance("MD5");
hash = md.digest(hashData);
keyAndIv = array_concat(keyAndIv, hash);
}
final byte[] keyValue = Arrays.copyOfRange(keyAndIv, 0, 32);
final SecretKeySpec key = new SecretKeySpec(keyValue, "AES");
final byte[] iv = Arrays.copyOfRange(keyAndIv, 32, 48);
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
final byte[] clear = cipher.doFinal(inBytes, 16, inBytes.length - 16);
return new String(clear, UTF_8);
}
private static byte[] array_concat(final byte[] a, final byte[] b) {
final byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
private static void removeCryptographyRestrictions() {
if (!isRestrictedCryptography()) {
return;
}
try {
/*
* Do the following, but with reflection to bypass access checks:
*
* JceSecurity.isRestricted = false; JceSecurity.defaultPolicy.perms.clear();
* JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE);
*/
final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity");
final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions");
final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission");
Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted");
isRestrictedField.setAccessible(true);
setFinalStatic(isRestrictedField, true);
isRestrictedField.set(null, false);
final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy");
defaultPolicyField.setAccessible(true);
final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);
final Field perms = cryptoPermissions.getDeclaredField("perms");
perms.setAccessible(true);
((Map<?, ?>) perms.get(defaultPolicy)).clear();
final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE");
instance.setAccessible(true);
defaultPolicy.add((Permission) instance.get(null));
}
catch (final Exception e) {
e.printStackTrace();
}
}
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
private static boolean isRestrictedCryptography() {
// This simply matches the Oracle JRE, but not OpenJDK.
return "Java(TM) SE Runtime Environment".equals(System.getProperty("java.runtime.name"));
}
}
I'm trying to migrate the oracle method dbms_obfuscation_toolkit.DES3Encrypt to a Java Function. My problem is that I don't get the same encrypted value in both scenes.
For this procedure in Oracle:
set serveroutput on;
declare
input raw(128);
encrypted raw(2048);
cadena varchar2(60);
begin
dbms_obfuscation_toolkit.DES3Encrypt(
input => utl_raw.cast_to_raw('TESTDATATESTDATATESTDATA'),
key => utl_raw.cast_to_raw('GD6GTT56HKY4HGF6FH3JG9J5F62FT1'),
encrypted_data => encrypted
);
dbms_output.put_line(rawtohex(encrypted));
end;
I get this output:
8A2E6792E39B0C850377F9A0E054033963F979E4A3FBA25B
However, with this Java class:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class TripleDes2
{
private static final String PLAIN_TEXT = "TESTDATATESTDATATESTDATA";
private static final String SHARED_KEY = "GD6GTT56HKY4HGF6FH3JG9J5F62FT1";
public static void main(String args []) throws Exception
{
String algorithm = "DESede";
String transformation = "DESede/CBC/PKCS5Padding";
byte[] keyValue = SHARED_KEY.getBytes("UTF-8");
DESedeKeySpec keySpec = new DESedeKeySpec(keyValue);
IvParameterSpec iv = new IvParameterSpec(new byte[8]);
SecretKey key = SecretKeyFactory.getInstance(algorithm).generateSecret(keySpec);
Cipher encrypter = Cipher.getInstance(transformation);
encrypter.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] input = PLAIN_TEXT.getBytes("UTF-8");
byte[] encrypted = encrypter.doFinal(input);
System.out.println(new String(Hex.encodeHex(encrypted)).toUpperCase());
}
}
I'm getting this value:
82EBC149F298DE55E4FF1540615E60ACDB7743FE79CD2CF4BB6FD232893F83D0
I'm not sure if my Java Code is right. Can you help me?
Thank you very much.
This is my final code, it works like a charm:
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
public class TripleDes3 {
private Cipher cipher = null;
private SecretKey key = null;
private byte[] bytes = null;
private IvParameterSpec iv = null;
public static void main(String[] args) throws Exception {
try {
String hexKey = "GD6GTT56HKY4HGF6FH3JG9J5";
//TripleDes3 encryptor = new TripleDes3(new String(Hex.decodeHex(hexKey.toCharArray())));
TripleDes3 encryptor = new TripleDes3(hexKey);
String original = "ABC";
System.out.println("Oringal: \"" + original + "\"");
String enc = encryptor.encrypt(original);
System.out.println("Encrypted: \"" + enc.toUpperCase() + "\"");
String dec = encryptor.decrypt(enc);
System.out.println("Decrypted: \"" + dec.toUpperCase() + "\"");
if (dec.equals(original)) {
System.out.println("Encryption ==> Decryption Successful");
}
} catch (Exception e) {
System.out.println("Error: " + e.toString());
}
}
public TripleDes3(String encryptionKey) throws GeneralSecurityException, DecoderException {
cipher = Cipher.getInstance("DESede/CBC/NoPadding");
try {
key = new SecretKeySpec(encryptionKey.getBytes("ISO8859_15"), "DESede");
iv = new IvParameterSpec(Hex.decodeHex("0123456789abcdef".toCharArray()));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String encrypt(String input) throws GeneralSecurityException, UnsupportedEncodingException {
bytes = input.getBytes("ISO8859_15");
bytes = Arrays.copyOf(bytes, ((bytes.length+7)/8)*8);
return new String(Hex.encodeHex(encryptB(bytes)));
}
public String decrypt(String input) throws GeneralSecurityException, DecoderException, UnsupportedEncodingException {
bytes = Hex.decodeHex(input.toCharArray());
String decrypted = new String(decryptB(bytes), "ISO8859_15");
if (decrypted.indexOf((char) 0) > 0) {
decrypted = decrypted.substring(0, decrypted.indexOf((char) 0));
}
return decrypted;
}
public byte[] encryptB(byte[] bytes) throws GeneralSecurityException {
cipher.init(Cipher.ENCRYPT_MODE, (Key) key, iv);
return cipher.doFinal(bytes);
}
public byte[] decryptB(byte[] bytes) throws GeneralSecurityException {
cipher.init(Cipher.DECRYPT_MODE, (Key) key, iv);
return cipher.doFinal(bytes);
}
}
And this is the Oracle Code:
DECLARE
v_data VARCHAR2(255);
v_retval RAW(255);
p_str VARCHAR2(255);
p_key RAW(255);
BEGIN
p_str := 'ABC';
p_key := utl_raw.cast_to_raw('GD6GTT56HKY4HGF6FH3JG9J5F62FT1');
v_data := RPAD(p_str, CEIL(LENGTH(p_str)/8)*8, CHR(0));
dbms_obfuscation_toolkit.DES3Encrypt
(
input => utl_raw.cast_to_raw(v_data),
key => p_key,
which => 1,
encrypted_data => v_retval
);
dbms_output.put_line(v_retval);
END;
Thanx to evry one help me ..but still there is 2 problem after editing the code
import java.io.*;
import java.math.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class RCC4 {
public RCC4(){}
public static void main(String[] args)throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException{
String test = "testisperfect";
System.out.println(RCC4.keyGet());
byte b[] = RCC4.keyGet().getBytes();
byte plain[] = test.getBytes();
**byte c[] = RCC4.encrypt(plain,b);**
**byte p[] = RCC4.decrypt(c,b);**
**System.out.println(new String(c)) ;
System.out.println(new String(p));**
}
public static byte[] encrypt(byte[] plaintext,byte[] keyBytes)
{
byte[] e = null;
try
{
Key key = new SecretKeySpec(keyBytes,"RC4");
Cipher enCipher = Cipher.getInstance("RC4");
**enCipher.init(Cipher.ENCRYPT_MODE ,key);**
e = enCipher.doFinal(plaintext);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return e;
}
public static byte[] decrypt(byte[] ciphertext,byte[] keyBytes)
{
byte de[] = null;
try
{
Key key = new SecretKeySpec(keyBytes,"RC4");
Cipher deCipher = Cipher.getInstance("RC4");
**deCipher.init(Cipher.DECRYPT_MODE, key);**
de = deCipher.doFinal(ciphertext);
}
catch(Exception e)
{
e.printStackTrace();
}
return de;
}
public static Key getKey()
{
Key key = null;
try
{
SecureRandom sr = new SecureRandom();
KeyGenerator kg = KeyGenerator.getInstance("RC4");
kg.init(128,sr);
key = kg.generateKey();
}catch(Exception e)
{
e.printStackTrace();
}
return key;
}
public static String keyGet()
{
Key k = RCC4.getKey();
byte[] b = k.getEncoded();
BigInteger big = new BigInteger(b);
String s = big.toString();
return s;
}
}
When I press "Build file" it says process completed but at running file a message says
112670544188765215715791498302542646231
java.security.InvalidKeyException: Illegal key size or default parameters
at RCC4.encrypt(RCC4.java:37)
at RCC4.main(RCC4.java:23)
java.security.InvalidKeyException: Illegal key size or default parameters
at RCC4.decrypt(RCC4.java:53)
at RCC4.main(RCC4.java:24)
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.<init>(String.java:479)
at RCC4.main(RCC4.java:26)
Process completed.
These Lines are indicated as *
Answer to original question:
Key key = new SecretKeySpec(byte[]keyBytes,RC4);
should be
Key key = new SecretKeySpec(keyBytes, "RC4");
Also,
deCipher.init(Cipher.WHATEVER, keyBytes);
should be
deCipher.init(Cipher.WHATEVER, key);
Then it compiles, however there's still some issue with the application logic. That's up to you again :).
Answer to new question:
The problem was the unneeded usage of SecretKeySpec. Somewhere between getKey(), keyGet() all the byte[] games and SecretKeySpec it got wrong somehow. I didn't have the patience to track it, so I just deleted it and made the code somewhat more readable to make sure I didn't miss anything. I think you will still understand it since it still is basically your code and it is much simpler now.
import java.security.*;
import javax.crypto.*;
public class RCC4 {
public static void main(String[] args) throws Exception {
String plain = "testisperfect";
Key key = RCC4.getKey();
String encrypted = RCC4.encrypt(plain, key);
String decrypted = RCC4.decrypt(encrypted, key);
System.out.println(encrypted);
System.out.println(decrypted);
}
private static String rc4(String plaintext, int mode, Key key) throws Exception {
Cipher cipher = Cipher.getInstance("RC4");
cipher.init(mode, key);
return new String(cipher.doFinal(plaintext.getBytes()));
}
public static String encrypt(String plaintext, Key key) throws Exception {
return rc4(plaintext, Cipher.ENCRYPT_MODE, key);
}
public static String decrypt(String ciphertext, Key key) throws Exception {
return rc4(ciphertext, Cipher.DECRYPT_MODE, key);
}
public static Key getKey() throws Exception {
KeyGenerator kg = KeyGenerator.getInstance("RC4");
SecureRandom sr = new SecureRandom();
kg.init(128, sr);
return kg.generateKey();
}
}
You need import SecretKeySpec which is under package javax.crypto.spec.
You're not calling the method correctly in that you're passing in the parameter type with the parameter. Parameter types are only shown when declaring a method, not when calling the method.
In other words, it's not
Key key = new SecretKeySpec(byte[] keyBytes, RC4);
it's instead
Key key = new SecretKeySpec(keyBytes, RC4);
You will of course need to have a keyBytes variable declared and initialized before trying to pass it into the parameter of this method.
package test;
import java.io.*;
import java.math.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class RCC4 {
public RCC4() {
}
public static void main(String[] args) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, IOException {
String test = "testisperfect";
System.out.println(RCC4.keyGet());
byte b[] = RCC4.keyGet().getBytes();
byte plain[] = test.getBytes();
byte c[] = RCC4.encrypt(plain, b);
byte p[] = RCC4.decrypt(c, b);
System.out.println(new String(c));
System.out.println(new String(p));
}
public static byte[] encrypt(byte[] plaintext, byte[] keyBytes) {
byte[] e = null;
try {
Key key = new SecretKeySpec(keyBytes, "RC4");
Cipher enCipher = Cipher.getInstance("RC4");
enCipher.init(Cipher.ENCRYPT_MODE, key);
e = enCipher.doFinal(plaintext);
} catch (Exception ex) {
ex.printStackTrace();
}
return e;
}
public static byte[] decrypt(byte[] ciphertext, byte[] keyBytes) {
byte de[] = null;
try {
Key key = new SecretKeySpec(keyBytes, "RC4");
Cipher deCipher = Cipher.getInstance("RC4");
deCipher.init(Cipher.DECRYPT_MODE, RCC4.getKey());
de = deCipher.doFinal(ciphertext);
} catch (Exception e) {
e.printStackTrace();
}
return de;
}
public static Key getKey() {
Key key = null;
try {
SecureRandom sr = new SecureRandom();
KeyGenerator kg = KeyGenerator.getInstance("RC4");
kg.init(128, sr);
key = kg.generateKey();
} catch (Exception e) {
e.printStackTrace();
}
return key;
}
public static String keyGet() {
Key k = RCC4.getKey();
byte[] b = k.getEncoded();
BigInteger big = new BigInteger(b);
String s = big.toString();
return s;
}
}