public void testWrapUnwrap2() {
try {
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(new SecureRandom());
SecretKey key = kg.generateKey();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(key);
oos.close();
byte[] keyBytes = baos.toByteArray();
Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
c.init(Cipher.ENCRYPT_MODE, key);
byte[] iv = c.getIV();
String clearText = "clear text";
byte[] cipherText = c.doFinal(clearText.getBytes());
byte[] salt = {
(byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
(byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
};
char[] password = { 'p','a','s','s','w','o','r','d' };
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWITHSHA256AND128BITAES-CBC-BC");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
Cipher pbeCipher = Cipher.getInstance("PBEWITHSHA256AND128BITAES-CBC-BC");
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
byte[] encryptedKeyBytes = pbeCipher.doFinal(keyBytes);
pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
keyBytes = pbeCipher.doFinal(encryptedKeyBytes);
ByteArrayInputStream bais = new ByteArrayInputStream(keyBytes);
ObjectInputStream ois = new ObjectInputStream(bais);
key = (SecretKey)ois.readObject();
ois.close():
c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] clearTextBytes = c.doFinal(cipherText);
String clearTextStr = new String(clearTextBytes);
Log.v("tag", clearTextStr);
}
catch (Exception e) { e.printStackTrace(); }
}
Thanks again.
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en
No comments:
Post a Comment