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
|
String b2File = ""; // string de taille % 8
DirContext ctx = this.getContext();
//récupère le certificat dont j'ai besoin
X509Certificate certificate = this.getCertificate(ctx);
this.closeContext(ctx);
try {
KeyStore ks = Utils.createCredentials(certificate);
byte[] plain_byte = b2File.getResult().getBytes();
PrivateKey privateKey = (PrivateKey) ks.getKey(Utils.ROOT_ALIAS, Utils.KEY_PASSWD);
Signature sign = Signature.getInstance("SHA1withRSA");
sign.initSign(privateKey);
sign.update(plain_byte);
byte[] plainSign = sign.sign();
KeyGenerator kg = KeyGenerator.getInstance("DESede");
kg.init(new SecureRandom());
Key sessionKey = kg.generateKey();
Cipher cph = Cipher.getInstance("DESede/CBC/NoPadding");
cph.init(Cipher.ENCRYPT_MODE,sessionKey);
byte[] cipher_byte = cph.doFinal(plain_byte);
byte[] iv = cph.getIV();
// cph = Cipher.getInstance("RSA/ECB/PKCS#1");
cph = Cipher.getInstance("RSA/ECB/NoPadding");
System.out.println(certificate);
cph.init(Cipher.ENCRYPT_MODE, certificate.getPublicKey());
byte[] cipherKey = cph.doFinal(sessionKey.getEncoded());
String ourDistName = certificate.getSubjectDN().toString();
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
DataOutputStream dataOutput = new DataOutputStream(byteOutput);
dataOutput.writeUTF(ourDistName);
dataOutput.writeInt(iv.length);
dataOutput.write(iv);
dataOutput.writeInt(cipherKey.length);
dataOutput.write(cipherKey);
dataOutput.writeInt(plainSign.length);
dataOutput.write(plainSign);
dataOutput.writeInt(cipher_byte.length);
dataOutput.write(cipher_byte);
byte[] cipher_bytes = byteOutput.toByteArray();
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.free.fr");
Session session = Session.getDefaultInstance(props, null);
Address fromUser = new InternetAddress("mon_adresse1@free.fr");
Address toUser = new InternetAddress("mon_adresse2@gmail.com");
MimeMessage message = new MimeMessage(session);
message.setFrom(fromUser);
message.setRecipient(Message.RecipientType.TO, toUser);
message.setSubject("Cipher Mail");
message.setText(new String(cipher_bytes));
Transport.send(message);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} |