1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| 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;
import javax.xml.bind.DatatypeConverter;
public class chiffrement {
public static final String TAG = "YourAppName";
private static String TRANSFORMATION = "AES/CBC/PKCS5PADDING";
private static String ALGORITHM = "AES";
private static String DIGEST = "MD5";
private static Cipher _cipher;
private static SecretKey _password;
private static IvParameterSpec _IVParamSpec;
// 16-byte private key
private static byte[] IV = "ThisIsUrPassword".getBytes();
/**
* Constructor
*
* @password Public key
*/
public chiffrement(String password) {
try {
// Encode digest
MessageDigest digest;
digest = MessageDigest.getInstance(DIGEST);
_password = new SecretKeySpec(digest.digest(password.getBytes()),
ALGORITHM);
// Initialize objects
_cipher = Cipher.getInstance(TRANSFORMATION);
_IVParamSpec = new IvParameterSpec(IV);
} catch (NoSuchAlgorithmException e) {
System.out.println(e.getMessage());
} catch (NoSuchPaddingException e) {
System.out.println(e.getMessage());
}
}
/**
* Encryptor.
*
* @text String to be encrypted
* @return Base64 encrypted text
*/
public String encrypt(byte[] text) {
byte[] encryptedData;
try {
_cipher.init(Cipher.ENCRYPT_MODE, _password, _IVParamSpec);
encryptedData = _cipher.doFinal(text);
} catch (InvalidKeyException e) {
System.out.println(e.getMessage());
return null;
} catch (InvalidAlgorithmParameterException e) {
System.out.println(e.getMessage());
return null;
} catch (IllegalBlockSizeException e) {
System.out.println(e.getMessage());
return null;
} catch (BadPaddingException e) {
System.out.println(e.getMessage());
return null;
}
return DatatypeConverter.printBase64Binary(encryptedData);
}
public static void main(String[] args) {
chiffrement r = new chiffrement("mypass");
String message ="MonPasse";
String messageCrypt = r.encrypt(message.getBytes());
System.out.println(message);
System.out.println(messageCrypt);
}
} |
Partager