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
|
public void Encryption(){ //C:\\MyFile.txt
File keyFile = new File("C:\\cipher\\public.crt");
byte[] encodedKey = new byte[(int) keyFile.length()];
try{
new FileInputStream(keyFile).read(encodedKey);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
// TEST
PublicKey pk = kf.generatePublic(publicKeySpec);
//
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pk);
byte[] cypherText = cipher.doFinal("Hello the world".getBytes("UTF8"));
System.out.println("Cryptés");
System.out.println(cypherText);
//
keyFile = new File("C:\\cipher\\privee.key");
encodedKey = new byte[(int) keyFile.length()];
new FileInputStream(keyFile).read(encodedKey);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
PrivateKey privateKey = (RSAPrivateKey)kf.generatePrivate(privateKeySpec);
cipher.init(Cipher.DECRYPT_MODE,privateKey);
System.out.println("decrypté");
System.out.println(cipher.doFinal(cypherText));
}
catch(Exception e){
logger.error(e.getMessage());
}
} |
Partager