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
|
// Fonction de création du certificat X509 :
public void encodeKey(){
X509EncodedKeySpec pks = new X509EncodedKeySpec(myPublicKey);
KeyFactory kf;
try {
kf = KeyFactory.getInstance("RSA");
publicKey = kf.generatePublic(pks);
} catch (Exception ex) {
ex.printStackTrace();
}
}
// Fonction de chiffrement RSA du tableau d'octets "data" :
public byte[] encrypt(byte[] data){
this.cmpt ++;
try
{
// On crée le crypteur :
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// On lance l'encryption en elle même :
byte[] ciphertext = new byte[1024];
int len = cipher.doFinal(data, 0, data.length, ciphertext, 0);
// On récupère le message encrypté et on corrige l'écart de 2 octets
// engendré par la spec qui veut que l'on ait un multiple de 8 :
// This is because I use a 142bytes key, while spec wants a 8 multiplicator,
// so I have two 0x00 padding bytes :
byte encrypted[] = new byte[len-2];
for(int i=0 ; i<encrypted.length ; i++){
encrypted[i] = ciphertext[i+2];
}
return encrypted;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
} |
Partager