I am making an application in blackberry. In that application i want to encrypt a string using AES algorithm. Is it possible to use AES algorithm in Blackberry? Is there any API for that? Thanks in advance,
try this -
useremail= CryptAes.AESEncryption(username_.getBytes());
CryptAes class is given below -
public class CryptAes {
// First create the AES key based on the bytes in secretKey using keyLength bits as the length
static AESKey keydec = new AESKey("A3$1E*81234567891111111111111111".getBytes() );
static AESKey keyenc = new AESKey("A3$1E*81234567891111111111111111".getBytes() );
static AESKey keyenc128 = new AESKey("A3Q1EF8123456789".getBytes());
static AESKey keydec128 = new AESKey("A3Q1EF8123456789".getBytes());
private static byte[] iv = { 0x0a, 0x01, 0x02, 0x03, 0x04, 0x0b, 0x0c,
0x0d, 0x0a, 0x01, 0x02, 0x03, 0x04, 0x0b, 0x0c, 0x0d };
public static byte[] plainText= new byte[10000];
public static String AESEncryption(byte[] plainText) throws CryptoException, IOException {
AESEncryptorEngine engine = new AESEncryptorEngine( keyenc128 );
CBCEncryptorEngine cengine=new CBCEncryptorEngine(engine, new InitializationVector(iv));
PKCS5FormatterEngine fengine = new PKCS5FormatterEngine( engine );
ByteArrayOutputStream output = new ByteArrayOutputStream();
BlockEncryptor encryptor = new BlockEncryptor( fengine, output );
encryptor.write(plainText);
encryptor.close();
byte[] encryptedData = output.toByteArray(); output.close();
String st=new String(encryptedData);
byte[] base64 = Base64OutputStream.encode(encryptedData, 0, encryptedData.length, false, false);
//Base64Coder.encodeString(Byte.toString(plainText));
String str = new String(base64);
return str;
}
// sampleAESDecryption
public static String AESDecryption(byte[] cipherText, int dataLength ) throws CryptoException, IOException {
// Create the input stream based on the ciphertext
ByteArrayInputStream in = new ByteArrayInputStream( cipherText, 0, dataLength );
// Now create the block decryptor and pass in a new instance
// of an AES decryptor engine with the specified block length
BlockDecryptor cryptoStream = new BlockDecryptor(new AESDecryptorEngine( keydec128 ), in );
byte[] T= new byte[dataLength];
// Read the decrypted text from the AES decryptor stream and
// return the actual length read
int length= cryptoStream.read( T );
String str= new String(T);
int i=str.indexOf("</msg>");
str=str.substring(0,i+6);
return str;
}
}
Look into AESEncryptorEngine and AESDecryptorEngine (with a help of Google).
Alternatively you may consider to use bouncy castle for j2me, as suggested here.
Related
I use the following lept4j and OpenCV Maven dependencies:
<!-- Leptonica -->
<dependency>
<groupId>net.sourceforge.lept4j</groupId>
<artifactId>lept4j</artifactId>
<version>1.9.0</version>
</dependency>
<!-- OpenCV -->
<dependency>
<groupId>org.openpnp</groupId>
<artifactId>opencv</artifactId>
<version>3.2.0-1</version>
</dependency>
I'd like to use OpenCV and Leptonica functions together. In order to do this, I need to be able to convert Mat to Pix and Pix to Mat.
This is what I have for now:
public static Pix matToGrayscalePix(Mat mat) {
if (mat == null) {
throw new IllegalArgumentException("Recycled matrix");
}
final byte[] bytes = new byte[(int) mat.total()];
mat.get(0, 0, bytes);
ByteBuffer buff = ByteBuffer.wrap(bytes);
return Leptonica1.pixReadMem(buff, new NativeSize(buff.capacity()));
}
public static Mat pixToGrayscaleMat(Pix pix) {
if (pix == null) {
throw new IllegalArgumentException("Recycled matrix");
}
PointerByReference pdata = new PointerByReference();
NativeSizeByReference psize = new NativeSizeByReference();
int format = net.sourceforge.lept4j.ILeptonica.IFF_TIFF;
Leptonica1.pixWriteMem(pdata, psize, pix, format);
byte[] b = pdata.getValue().getByteArray(0, psize.getValue().intValue());
return new MatOfByte(b).reshape(0, pix.h);
}
But these functions doesn't work right now. What am I doing wrong ?
Try the following:
public static Pix convertMatToPix(Mat mat) {
MatOfByte bytes = new MatOfByte();
Imgcodecs.imencode(".tif", mat, bytes);
ByteBuffer buff = ByteBuffer.wrap(bytes.toArray());
return Leptonica1.pixReadMem(buff, new NativeSize(buff.capacity()));
}
public static Mat convertPixToMat(Pix pix) {
PointerByReference pdata = new PointerByReference();
NativeSizeByReference psize = new NativeSizeByReference();
Leptonica1.pixWriteMem(pdata, psize, pix, ILeptonica.IFF_TIFF);
byte[] b = pdata.getValue().getByteArray(0, psize.getValue().intValue());
Leptonica1.lept_free(pdata.getValue());
return Imgcodecs.imdecode(new MatOfByte(b), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);
}
I would like to convert the below Java aes encryption to objective c. Anyone who has knowledge in both Java and Objective C please help. Any help will be greatly appreciated. Can anyone help by providing the details of encryption method used?
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Crypto {
public static final String TAG = Crypto.class.getSimpleName();
// Replace me with a 16-byte key, share between Java and C#
private static Cipher aesCipher;
private static SecretKey secretKey;
private static IvParameterSpec ivParameterSpec;
private static String CIPHER_TRANSFORMATION = "AES/CBC/PKCS5Padding";
private static String CIPHER_ALGORITHM = "AES";
private static byte[] rawSecretKey = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
// private static String MESSAGEDIGEST_ALGORITHM = "MD5";
private static String MESSAGEDIGEST_ALGORITHM = "SHA-256";
public Crypto(String passphrase) {
byte[] passwordKey = encodeDigest(passphrase);
try {
aesCipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "No such algorithm " + CIPHER_ALGORITHM, e);
} catch (NoSuchPaddingException e) {
Log.e(TAG, "No such padding PKCS5", e);
}
secretKey = new SecretKeySpec(passwordKey, CIPHER_ALGORITHM);
ivParameterSpec = new IvParameterSpec(rawSecretKey);
}
public byte[] decrypt(byte[] clearData) {
try {
aesCipher.init(Cipher.DECRYPT_MODE, secretKey);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
byte[] decryptedData;
try {
decryptedData = aesCipher.doFinal(clearData);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
return null;
} catch (BadPaddingException e) {
e.printStackTrace();
return null;
}
return decryptedData;
}
public String decryptAsBase64(byte[] clearData) throws IOException {
byte[] decryptedData = decrypt(clearData);
return new String(Base64New.decode(decryptedData));
}
public String encryptAsBase64(byte[] clearData) {
byte[] encryptedData = encrypt(clearData);
return Base64New.encodeBytes(encryptedData);
}
public byte[] encrypt(byte[] clearData) {
try {
aesCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
} catch (InvalidKeyException e) {
Log.e(TAG, "Invalid key", e);
return null;
} catch (InvalidAlgorithmParameterException e) {
Log.e(TAG, "Invalid algorithm " + CIPHER_ALGORITHM, e);
return null;
}
byte[] encryptedData;
try {
encryptedData = aesCipher.doFinal(clearData);
} catch (IllegalBlockSizeException e) {
Log.e(TAG, "Illegal block size", e);
return null;
} catch (BadPaddingException e) {
Log.e(TAG, "Bad padding", e);
return null;
}
return encryptedData;
}
private byte[] encodeDigest(String text) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance(MESSAGEDIGEST_ALGORITHM);
return digest.digest(text.getBytes());
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "No such algorithm " + MESSAGEDIGEST_ALGORITHM, e);
}
return null;
}
}
Here are the details of encryption method used:
The encryption is AES in CBC mode with PKCS#5 padding (PKCS#7 padding is the same here).
The CBC mode has an iv as input, the iv is the rawSecretKey which is all 0 bytes (not a best practice).
The encryption passwordKey is derived from the secretKey using SHA-256 (not a best practice).
Additionally there are methods to add and remove Base64 encoding.
I have the following C code that uses libmodbus to read a single device register using ModbusTCP:
modbus_t *ctx;
uint16_t tab_reg[16];
ctx = modbus_new_tcp("10.0.1.77", 502);
modbus_read_registers(ctx, 0x20, 2, tab_reg);
printf("reg = %d (0x%X)\n", tab_reg[0], tab_reg[0]);
printf("reg = %d (0x%X)\n", tab_reg[1], tab_reg[1]);
now trying to switch this over to Vala using a Vapi that I've generated, the contents of that for new and read are:
[CCode (cheader_filename = "modbus.h", cname = "modbus_new_tcp")]
public static unowned Modbus.modbus_t create_tcp (string ip_address, int port);
public static int read_registers (Modbus.modbus_t ctx, int addr, int nb, uint16 dest);
[CCode (cheader_filename = "modbus.h")]
and the translated Vala program is:
class ModbusReadTest : GLib.Object {
unowned Modbus.modbus_t ctx;
public void run () {
uint16 reg = 0x00;
ctx = create_tcp ("10.0.1.77", 502);
Modbus.read_registers (ctx, 0x20, 2, reg);
message ("reg = %d (0x%X)", reg, reg);
Modbus.close(ctx);
}
}
Coincidentally, when I compile this into C code and then into a binary using gcc I get the error:
read-registers-test.c:71:2: warning: passing argument 4 of ‘modbus_read_registers’ makes pointer from integer without a cast [enabled by default]
which is not surprising. But I'm not sure how I should go about modifying the Vapi contents to closer match the prototype in the libmodbus header:
int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest);
I've tried a mix of array options and using 'out', but haven't been able to get more than a single double byte register at a time.
read_registers should probably be an instance method (on Modbus.modbus_t) instead of a static method, and Modbus.modbus_t should probably be renamed to something like Modbus.Context, create_tcp should probably be a constructor, and Modbus.close should be a free function on the Modbus.Context compact class, but that's beside the point of this question (if you stop by #vala on irc.gnome.org you can get help with that stuff).
You probably want to make it an array:
public static int read_registers (Modbus.modbus_t ctx, int addr, [CCode (array_length_pos = 2.5)] uint16[] dest);
Then you would do something like this in Vala:
public void run () {
uint16 reg[2];
ctx = create_tcp ("10.0.1.77", 502);
Modbus.read_registers (ctx, 0x20, reg);
message ("reg = %d (0x%X)", reg, reg);
Modbus.close(ctx);
}
For a port more faithful to the original C (where tab_reg has 16 elements instead of 2), you could use array slicing:
public void run () {
uint16 reg[16];
ctx = create_tcp ("10.0.1.77", 502);
Modbus.read_registers (ctx, 0x20, reg[0:2]);
stdout.printf ("reg = %d (0x%X)\n", reg, reg);
Modbus.close(ctx);
}
Note that if you make it an instance method you'll need to change the array_length_pos to 1.5.
I need a bitmap ARRAY ready to be used dynamically.
what i did is.
on Activity i put
public static Bitmap[] bitmapArray;
bitmapArray = new Bitmap[10];
then to use with a timer i do
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(),
IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
// options.outHeight=50;
// options.outWidth=50;
// options.inScaled=true; //inSampleSize = 1;
// options.inSampleSize=3;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
options);
} catch (IOException e) {
e.printStackTrace();
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
for i.........
MyActivity.bitmapArray[i]= loadBitmap( url........
And this is the problem. if i have on the heap a block of 10 (Bitmap[10])
bitmaps buffers i want it to stay fix!!Same memory location.
but each timer iteration the program load the buffer to a DIFFERENT block location
which very soon the memory is finished.
any idea?
P.S i need the above solution fixed since i need the bitmap buffer to be used fast.
What is the best way to encrypt an URL with parameters in Java?
The only way to do this is to use SSL/TLS (https). If you use plain old HTTP, the URL will definitely be sent in the clear.
Unfortunatelly almost noting is simple in java :-) , for this simple and usual task I wasnt able to find a prepared library, I ended up writing this (this was the source):
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEParameterSpec;
/**
* An easy to use class to encrypt and decrypt a string. Just call the simplest
* constructor and the needed methods.
*
*/
public class StringEncryptor {
private Cipher encryptCipher;
private Cipher decryptCipher;
private sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
private sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
final private String charset = "UTF-8";
final private String defaultEncryptionPassword = "PAOSIDUFHQWER98234QWE378AHASDF93HASDF9238HAJSDF923";
final private byte[] defaultSalt = {
(byte) 0xa3, (byte) 0x21, (byte) 0x24, (byte) 0x2c,
(byte) 0xf2, (byte) 0xd2, (byte) 0x3e, (byte) 0x19 };
/**
* The simplest constructor which will use a default password and salt to
* encode the string.
*
* #throws SecurityException
*/
public StringEncryptor() throws SecurityException {
setupEncryptor(defaultEncryptionPassword, defaultSalt);
}
/**
* Dynamic constructor to give own key and salt to it which going to be used
* to encrypt and then decrypt the given string.
*
* #param encryptionPassword
* #param salt
*/
public StringEncryptor(String encryptionPassword, byte[] salt) {
setupEncryptor(encryptionPassword, salt);
}
public void init(char[] pass, byte[] salt, int iterations) throws SecurityException {
try {
PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt, 20);
SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pass));
encryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, k, ps);
decryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, k, ps);
} catch (Exception e) {
throw new SecurityException("Could not initialize CryptoLibrary: " + e.getMessage());
}
}
/**
*
* method to decrypt a string.
*
* #param str
* Description of the Parameter
*
* #return String the encrypted string.
*
* #exception SecurityException
* Description of the Exception
*/
public synchronized String encrypt(String str) throws SecurityException {
try {
byte[] utf8 = str.getBytes(charset);
byte[] enc = encryptCipher.doFinal(utf8);
return URLEncoder.encode(encoder.encode(enc),charset);
}
catch (Exception e)
{
throw new SecurityException("Could not encrypt: " + e.getMessage());
}
}
/**
*
* method to encrypting a string.
*
* #param str
* Description of the Parameter
*
* #return String the encrypted string.
*
* #exception SecurityException
* Description of the Exception
*/
public synchronized String decrypt(String str) throws SecurityException {
try {
byte[] dec = decoder.decodeBuffer(URLDecoder.decode(str,charset));
byte[] utf8 = decryptCipher.doFinal(dec);
return new String(utf8, charset);
} catch (Exception e) {
throw new SecurityException("Could not decrypt: " + e.getMessage());
}
}
private void setupEncryptor(String defaultEncryptionPassword, byte[] salt) {
java.security.Security.addProvider(new com.sun.crypto.provider.SunJCE());
char[] pass = defaultEncryptionPassword.toCharArray();
int iterations = 3;
init(pass, salt, iterations);
}
}
java security api(http://java.sun.com/javase/technologies/security/) + url encoding
It depends on your threat model. For example, if you want to protect the parameters sent by your Java app to your server from an attacker who has access to the communication channel, you should consider communicating with the server via TLS/SSL (i.e., HTTPS in your case) and the likes. If you want to protect the parameters from an attacker who has access to the machine where your Java client app runs, then you're in deeper trouble.
If you really can't use SSL, I'd suggest a pre-shared key approach and adding a random iv.
You can use any decent symmetric encryption method ex. AES using a pre-shared key you're communicating out of band (email, phone etc.).
Then you generate a random initialization vector and encrypt your string with this iv and the key. Finally you concatenate your cipher text and the iv and send this as your parameter. The iv can be communicated in the clear without any risk.
The standard way to encrypt HTTP traffic is to use SSL. However, even over HTTPS, the URL and any parameters in it (i.e. a GET request) will be sent in the clear. You would need to use SSL and do a POST request to properly encrypt your data.
As pointed out in the comments parameters will be encrypted no matter what HTTP method you use, as long as you use an SSL connection.
Are you sure you don't mean URL encode?
Encoding is available through java.net.URLEncoder.encode.