Я пытаюсь отправить цифровое подписанное/защищенное письмо с использованием API JavaMAIL.Можно ли отправить защищенную почту без ведомостей отправителя?
Для этого я создал сертификат KEYSTORE и использовал (загруженный через bouncycastle) это при создании этой почты и отправки ее пользователю. Но я должен предоставить имя пользователя и пароль идентификатора почты отправителя для аутентификации.
Есть ли способ отправить защищенную почту без ведомостей отправителя?
Я попытался сделать аутентификацию ложной. но не повезло.
props.put("mail.smtp.auth", "true"); //enable authentication
Мой код :::
public static void main(String[] args) {
final String fromEmail = "[email protected]"; //requires valid gmail id
final String toEmail = "[email protected]";
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "132.000.000.001"); //SMTP Host
props.put("mail.smtp.port", "587"); //TLS Port
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
props.put("mail.smtp.ssl.trust", "*");
props.put("mail.debug", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("MYUSERNAME","MYPASSWORD");
}
});
boolean isAlias = false;
//Session session = Session.getDefaultInstance(props);
System.out.println("SESSION CREATED..............");
try {
// Add BouncyCastle content handlers to command map
MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mailcap.addMailcap("multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");
CommandMap.setDefaultCommandMap(mailcap);
Security.addProvider(new BouncyCastleProvider());
KeyStore keyStore = KeyStore.getInstance("JKS");
// Provide location of Java Keystore and password for access
keyStore.load(new FileInputStream("D:\\CERTIFICATES\\MAIL_CERT\\selfservice.cert"),
"keystore".toCharArray());
// Find the first legit alias in the keystore and use it
Enumeration<String> es = keyStore.aliases();
String alias = "";
while (es.hasMoreElements()) {
alias = (String) es.nextElement();
// Does alias refer to a private key? Assign true/false to isAlias & evaluate
if (isAlias = keyStore.isKeyEntry(alias)) {
break;
}
}
if (isAlias) {
KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection("keystore".toCharArray()));
PrivateKey myPrivateKey = pkEntry.getPrivateKey();
// Load certificate chain
Certificate[] chain = keyStore.getCertificateChain(alias);
// Create the SMIMESignedGenerator
SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
capabilities.addCapability(SMIMECapability.dES_CBC);
capabilities.addCapability(SMIMECapability.aES256_CBC);
ASN1EncodableVector attributes = new ASN1EncodableVector();
attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(
new IssuerAndSerialNumber(
new X500Name(((X509Certificate) chain[0])
.getIssuerDN().getName()),
((X509Certificate) chain[0]).getSerialNumber())));
attributes.add(new SMIMECapabilitiesAttribute(capabilities));
SMIMESignedGenerator signer = new SMIMESignedGenerator();
signer.addSigner(
myPrivateKey,
(X509Certificate) chain[0],
"DSA".equals(myPrivateKey.getAlgorithm()) ? SMIMESignedGenerator.DIGEST_SHA1
: SMIMESignedGenerator.DIGEST_MD5,
new AttributeTable(attributes), null);
// Add the list of certs to the generator
List certList = new ArrayList();
certList.add(chain[0]);
CertStore certs = CertStore.getInstance("Collection",
new CollectionCertStoreParameters(certList), "BC");
signer.addCertificatesAndCRLs(certs);
// Construct the message body
MimeMessage body = new MimeMessage(session);
body.setFrom(new InternetAddress(fromEmail));
body.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
body.setContent("DEAR.....BODY....", "text/plain");
body.saveChanges();
// Sign the message
MimeMultipart mm = signer.generate(body, "BC");
MimeMessage signedMessage = new MimeMessage(session);
signedMessage.setFrom(new InternetAddress(fromEmail));
signedMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
signedMessage.setSubject("Testing Signed Subject");
// Set the content of the signed message
signedMessage.setContent(mm);
signedMessage.saveChanges();
// Send the message
Transport.send(signedMessage);
}
} catch (MessagingException e) {
throw new RuntimeException(e);
} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | UnrecoverableEntryException |
InvalidAlgorithmParameterException | NoSuchProviderException | CertStoreException |SMIMEException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
С какой ошибкой вы сталкиваетесь? Отправка электронной почты, очевидно, не зависит от каких-либо учетных данных, кроме ваших (для авторизации SMTP), и для шифрования потребуется только открытый ключ приемников (который является hmm ** public **.) – Jan