'ssl'에 해당되는 글 3건

  1. 2017.02.06 [HttpClient] javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name
  2. 2017.02.02 [AWS] ELB + http to https + Nginx 설정
  3. 2012.05.02 javamail pop3 ssl 적용.

[HttpClient] javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name

ITWeb/개발일반 2017. 2. 6. 11:33

http 통신 기능 구현 시 아래와 같은 에러를 접하는 경우가 있어서 해결 방법을 기록해 봅니다.


[에러내용]

javax.net.ssl.SSLProtocolException: handshake alert:  unrecognized_name

    at sun.security.ssl.ClientHandshaker.handshakeAlert(ClientHandshaker.java:1441)

    at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:2016)

    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1125)

    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)

    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)

    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)

    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:394)

    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:353)

    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:141)



[해결방법]

JVM 실행 시 옵션 추가)

-Djsse.enableSNIExtension=false


Application 내부에서 설정 추가)

System.setProperty(“jsse.enableSNIExtension”, “false”);

:

[AWS] ELB + http to https + Nginx 설정

ITWeb/개발일반 2017. 2. 2. 10:12

요즘 대부분의 서비스들이 http 를 제거 하고 https 로 서비스 하기 시작했습니다.

AWS 에서 제공하는 SSL 을 이용해서 ELB 에 구성하신 분들의 경우 대부분 아래와 같이 되어 있을 것 같은데요.


http://service    -> elb:80   -> ec2:80

https://service  -> elb:443  -> ec2:80


이와 같이 되어 있다 보니 개별 ec2 에서는 모두 listen 80 만 하게 됩니다.

그래서 client 에서 http 로 들어 왔는지 https 로 들어 왔는지 확인이 필요 한데요.

이 경우 아래와 같은 변수들을 활용해서 설정을 하시면 됩니다.


[참고문서]

http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html


[X-Forwarded Headers]

X-Forwarded-For

X-Forwarded-Proto

X-Forwarded-Port


[Nginx 설정]

server {

  listen       80;

  server_name  localhost;


  if ($http_x_forwarded_proto = 'http') {

    return 301 https://$server_name$request_uri;

  }

}


참고 용이니 실 서비스에 적용 시 충분한 테스트 후 적용하시기 바랍니다.

:

javamail pop3 ssl 적용.

ITWeb/개발일반 2012. 5. 2. 20:47

그냥 일반 웹메일에서 외부메일 가져오기로 기능 확인 하려다 삽질만 했내요.
기냥 코딩 할걸..ㅡ.ㅡ;;
- 네이버 메일에서 외부메일 가져오기는 SSL 지원이 없구요.
- G메일에서는 SSL Port 변경이 없내요..

javamail api 를 이용해서 구현 가능합니다.
아래는 샘플 코드 이구요.
퍼왔습니다.

[원본링크]


[샘플코드]

You can use following utility class to conect to Gmail. Since Gmail only supports POP3 connection with SSL, the connection is established via SSL.

package org.javatipsjavaemaillistimporter;

import com.sun.mail.pop3.POP3SSLStore;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.ContentType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.ParseException;

public class GmailUtilities {
    
    private Session session = null;
    private Store store = null;
    private String username, password;
    private Folder folder;
    
    public GmailUtilities() {
        
    }
    
    public void setUserPass(String username, String password) {
        this.username = username;
        this.password = password;
    }
    
    public void connect() throws Exception {
        
        String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        
        Properties pop3Props = new Properties();
        
        pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        pop3Props.setProperty("mail.pop3.socketFactory.fallback""false");
        pop3Props.setProperty("mail.pop3.port",  "995");
        pop3Props.setProperty("mail.pop3.socketFactory.port""995");
        
        URLName url = new URLName("pop3""pop.gmail.com"995"",
                username, password);
        
        session = Session.getInstance(pop3Props, null);
        store = new POP3SSLStore(session, url);
        store.connect();
        
    }
    
    public void openFolder(String folderNamethrows Exception {
        
        // Open the Folder
        folder = store.getDefaultFolder();
        
        folder = folder.getFolder(folderName);
        
        if (folder == null) {
            throw new Exception("Invalid folder");
        }
        
        // try to open read/write and if that fails try read-only
        try {
            
            folder.open(Folder.READ_WRITE);
            
        catch (MessagingException ex) {
            
            folder.open(Folder.READ_ONLY);
            
        }
    }
    
    public void closeFolder() throws Exception {
        folder.close(false);
    }
    
    public int getMessageCount() throws Exception {
        return folder.getMessageCount();
    }
    
    public int getNewMessageCount() throws Exception {
        return folder.getNewMessageCount();
    }
    
    public void disconnect() throws Exception {
        store.close();
    }
    
    public void printMessage(int messageNothrows Exception {
        System.out.println("Getting message number: " + messageNo);
        
        Message m = null;
        
        try {
            m = folder.getMessage(messageNo);
            dumpPart(m);
        catch (IndexOutOfBoundsException iex) {
            System.out.println("Message number out of range");
        }
    }
    
    public void printAllMessageEnvelopes() throws Exception {
        
        // Attributes & Flags for all messages ..
        Message[] msgs = folder.getMessages();
        
        // Use a suitable FetchProfile
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);        
        folder.fetch(msgs, fp);
        
        for (int i = 0; i < msgs.length; i++) {
            System.out.println("--------------------------");
            System.out.println("MESSAGE #" (i + 1":");
            dumpEnvelope(msgs[i]);
            
        }
        
    }
    
    public void printAllMessages() throws Exception {
     
        // Attributes & Flags for all messages ..
        Message[] msgs = folder.getMessages();
        
        // Use a suitable FetchProfile
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);        
        folder.fetch(msgs, fp);
        
        for (int i = 0; i < msgs.length; i++) {
            System.out.println("--------------------------");
            System.out.println("MESSAGE #" (i + 1":");
            dumpPart(msgs[i]);
        }
        
    
    }
    
    
    public static void dumpPart(Part pthrows Exception {
        if (instanceof Message)
            dumpEnvelope((Message)p);
       
        String ct = p.getContentType();
        try {
            pr("CONTENT-TYPE: " (new ContentType(ct)).toString());
        catch (ParseException pex) {
            pr("BAD CONTENT-TYPE: " + ct);
        }
        
        /*
         * Using isMimeType to determine the content type avoids
         * fetching the actual content data until we need it.
         */
        if (p.isMimeType("text/plain")) {
            pr("This is plain text");
            pr("---------------------------");
            System.out.println((String)p.getContent());        
        else {
            
            // just a separator
            pr("---------------------------");
            
        }
    }
    
    public static void dumpEnvelope(Message mthrows Exception {        
        pr(" ");
        Address[] a;
        // FROM
        if ((a = m.getFrom()) != null) {
            for (int j = 0; j < a.length; j++)
                pr("FROM: " + a[j].toString());
        }
        
        // TO
        if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
            for (int j = 0; j < a.length; j++) {
                pr("TO: " + a[j].toString());                
            }
        }
        
        // SUBJECT
        pr("SUBJECT: " + m.getSubject());
        
        // DATE
        Date d = m.getSentDate();
        pr("SendDate: " +
                (d != null ? d.toString() "UNKNOWN"));
        

    }
    
    static String indentStr = "                                               ";
    static int level = 0;
    
    /**
     * Print a, possibly indented, string.
     */
    public static void pr(String s) {
        
        System.out.print(indentStr.substring(0, level * 2));
        System.out.println(s);
    }
    
}

And the following code snippet shows how to use the above utility class. You can uncomment printAllMessageEnvelopes() method to just print the envelopes of the messages instead of whole messages.

package org.javatipsjavaemaillistimporter;

public class Main {
    
    /** Creates a new instance of Main */
    public Main() {
    }
    
    /**
     @param args the command line arguments
     */
    public static void main(String[] args) {
        
        try {
            
            GmailUtilities gmail = new GmailUtilities();
            gmail.setUserPass(myemail@gmail.com""mypassword");
            gmail.connect();
            gmail.openFolder("INBOX");
            
            int totalMessages = gmail.getMessageCount();
            int newMessages = gmail.getNewMessageCount();
            
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
            
            //gmail.printAllMessageEnvelopes();
            gmail.printAllMessages();
            
        catch(Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
        
    }
    
}


: