IT 한길

[LDAP SSL] TEST

Progamming/LDAP2012. 12. 4. 11:27

package com.imws;

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import javax.naming.directory.*;
import javax.naming.*;

 

public class TestLpap {

 
 
 public static void main(String[] args) {
  
  
  /*TestLpap test = new TestLpap();
  test.PrintCertInfo();
  test.PrintCertFromKeyStrore();*/
  
  String keystorePath = System.getProperty("java.home") +"/lib/security/jssecacerts";

  System.setProperty("javax.net.ssl.keyStore", keystorePath);

  System.setProperty("javax.net.ssl.keyStorePassword", "imsi00.!");

 


  
  Hashtable<String, Object> env = new Hashtable<String, Object>(11);
     env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
     env.put(Context.PROVIDER_URL, "ldap://192.168.0.233:20390");

     // Specify SSL
    env.put(Context.SECURITY_PROTOCOL, "ssl");
    
     //env.put(Context.PROVIDER_URL, "ldap://192.168.0.233:20389");

 


     // Authenticate as S. User and password "mysecret"
     env.put(Context.SECURITY_AUTHENTICATION, "simple");
     env.put(Context.SECURITY_PRINCIPAL, "eTGlobalUserName=imadmin,eTGlobalUserContainerName=Global Users,eTNamespaceName=CommonObjects,dc=im,dc=eta");
     env.put(Context.SECURITY_CREDENTIALS, "imsi00.!");

     try {
       // Create initial context
       DirContext ctx = new InitialDirContext(env);

       System.out.println("==========="+ctx.lookup("dc=im,dc=eta"));
      
      
       SearchControls searchCtls = new SearchControls();
   
   //Specify the attributes to return
   String returnedAtts[]={"dn","objectClass"};
   searchCtls.setReturningAttributes(returnedAtts);
  
   //Specify the search scope
   searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

   //specify the LDAP search filter
   String searchFilter = "(objectClass=eTNamespace)";

   //Specify the Base for the search
   String searchBase = "dc=im,dc=eta";

   //initialize counter to total the results
   int totalResults = 0;


   // Search for objects using the filter
   NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);

   //Loop through the search results
   while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult)answer.next();

    totalResults++;

    System.out.println(">>>" + sr.getName());

    // Print out some of the attributes, catch the exception if the attributes have no values
    Attributes attrs = sr.getAttributes();
    if (attrs != null) {
     try {
     System.out.println("   surname: " + attrs.get("dn").get());
     System.out.println("   firstname: " + attrs.get("objectClass").get());

     }
     catch (NullPointerException e) {
     System.out.println("Errors listing attributes: " + e);
     }
    }

   }

   System.out.println("Total results: " + totalResults);
   ctx.close();


       // ... do something useful with ctx

       // Close the context when we're done
       ctx.close();
     } catch (NamingException e) {
       e.printStackTrace();
     }

 }
}

 

'Progamming > LDAP' 카테고리의 다른 글

[LDAP SSL]Connection  (0) 2012.12.04
[LDAP SSL]InstallCert  (0) 2012.12.04
[LDAP SSL]인증서 생성  (0) 2012.12.04

package com.imws;
/*
 * @(#)InstallCert.java 1.1 06/10/09
 *
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 * Use is subject to license terms.
 */

import java.io.*;
import java.net.URL;

import java.security.*;
import java.security.cert.*;

import javax.net.ssl.*;

public class InstallCert {

    public static void main(String[] args) throws Exception {
 String host;
 int port;
 args = new String[2];
 args[0]="192.168.0.233:20390";
 args[1]="password";
 char[] passphrase;
 if ((args.length == 1) || (args.length == 2)) {
     String[] c = args[0].split(":");
     host = c[0];
     port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
     String p = (args.length == 1) ? "changeit" : args[1];
     System.out.println("Loading KeyStore " + p + "...");
     passphrase = p.toCharArray();
 } else {
     System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
     return;
 }

 File file = new File("jssecacerts");
 if (file.isFile() == false) {
     char SEP = File.separatorChar;
     File dir = new File(System.getProperty("java.home") + SEP
      + "lib" + SEP + "security");
     file = new File(dir, "jssecacerts");
     if (file.isFile() == false) {
  file = new File(dir, "cacerts");
     }
 }
 InputStream in = new FileInputStream(file);
 
 KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
 
 ks.load(in, passphrase);
 in.close();
 System.out.println("Loading dd " +  ks + "...");
 SSLContext context = SSLContext.getInstance("TLS");
 TrustManagerFactory tmf =
     TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
 tmf.init(ks);
 X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
 SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
 context.init(null, new TrustManager[] {tm}, null);
 SSLSocketFactory factory = context.getSocketFactory();
 
 System.out.println("Opening connection to " + host + ":" + port + "...");
 SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
 socket.setSoTimeout(10000);
 try {
     System.out.println("Starting SSL handshake...");
     socket.startHandshake();
     socket.close();
     System.out.println();
     System.out.println("No errors, certificate is already trusted");
 } catch (SSLException e) {
     System.out.println();
     e.printStackTrace(System.out);
 }

 X509Certificate[] chain = tm.chain;
 if (chain == null) {
     System.out.println("Could not obtain server certificate chain");
     return;
 }

 BufferedReader reader =
  new BufferedReader(new InputStreamReader(System.in));

 System.out.println();
 System.out.println("Server sent " + chain.length + " certificate(s):");
 System.out.println();
 MessageDigest sha1 = MessageDigest.getInstance("SHA1");
 MessageDigest md5 = MessageDigest.getInstance("MD5");
 for (int i = 0; i < chain.length; i++) {
     X509Certificate cert = chain[i];
     System.out.println
      (" " + (i + 1) + " Subject " + cert.getSubjectDN());
     System.out.println("   Issuer  " + cert.getIssuerDN());
     sha1.update(cert.getEncoded());
     System.out.println("   sha1    " + toHexString(sha1.digest()));
     md5.update(cert.getEncoded());
     System.out.println("   md5     " + toHexString(md5.digest()));
     System.out.println();
 }

 System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
 String line = reader.readLine().trim();
 int k;
 try {
     k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
 } catch (NumberFormatException e) {
     System.out.println("KeyStore not changed");
     return;
 }

 X509Certificate cert = chain[k];
 String alias = host + "-" + (k + 1);
 ks.setCertificateEntry(alias, cert);

 OutputStream out = new FileOutputStream("jssecacerts");
 ks.store(out, passphrase);
 out.close();

 System.out.println();
 System.out.println(cert);
 System.out.println();
 System.out.println
  ("Added certificate to keystore 'jssecacerts' using alias '"
  + alias + "'");
    }
   
    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
   
    private static String toHexString(byte[] bytes) {
 StringBuilder sb = new StringBuilder(bytes.length * 3);
 for (int b : bytes) {
     b &= 0xff;
     sb.append(HEXDIGITS[b >> 4]);
     sb.append(HEXDIGITS[b & 15]);
     sb.append(' ');
 }
 return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {
 
 private final X509TrustManager tm;
 private X509Certificate[] chain;
 
 SavingTrustManager(X509TrustManager tm) {
     this.tm = tm;
 }
   
 public X509Certificate[] getAcceptedIssuers() {
     throw new UnsupportedOperationException();
 }
   
 public void checkClientTrusted(X509Certificate[] chain, String authType)
  throws CertificateException {
     throw new UnsupportedOperationException();
 }
   
 public void checkServerTrusted(X509Certificate[] chain, String authType)
  throws CertificateException {
     this.chain = chain;
     tm.checkServerTrusted(chain, authType);
 }
    }

}

'Progamming > LDAP' 카테고리의 다른 글

[LDAP SSL]Connection  (0) 2012.12.04
[LDAP SSL] TEST  (0) 2012.12.04
[LDAP SSL]인증서 생성  (0) 2012.12.04

1.키툴로 인증서 생성하기

keytool -genkey -alias ldap

2.키저장소 엔트리 확인

keytool -v -list

3.키 저장소로부터 인증서 추출

keytool -export -alias ldap -file ldap.cer

 

4.인증서 보기 예제

import java.io.FileInputStream;

import java.security.cert.Certificate;

import java.security.cert.CertificateFactory;

 

public class PrintCertInfo {

 

       public static void main(String[] args) throws Exception {

             CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

             FileInputStream fis = new FileInputStream("c:\\ldap.cer");

             Certificate cert = certFactory.generateCertificate(fis);

             fis.close();

             System.out.println(cert);

       }

}

[출처] [암호화] 전자 인증서|작성자 버들

 

 

5.키저장소로부터 인증서를 읽어 들이는 예제

import java.io.File;

import java.io.FileInputStream;

import java.security.KeyStore;

import java.security.cert.Certificate;

 

public class PrintCertFromKeyStore {

 

       public static void main(String[] args) throws Exception {

             String userHome = System.getProperty("user.home");

             String keyStoreFileName = userHome + File.separator + ".keystore";

            

             // keystore 대한 패스워드와 엔트리에 대한 alias 지정

             char[] password = "password".toCharArray();

             String alias = "test";

            

             FileInputStream fis = new FileInputStream(keyStoreFileName);

             KeyStore keyStore = KeyStore.getInstance("JKS");

             keyStore.load(fis, password);

            

             Certificate cert = keyStore.getCertificate(alias);

             System.out.println(cert);

       }

}

 

'Progamming > LDAP' 카테고리의 다른 글

[LDAP SSL]Connection  (0) 2012.12.04
[LDAP SSL] TEST  (0) 2012.12.04
[LDAP SSL]InstallCert  (0) 2012.12.04

The JBoss AS 5.1 server does not support the service project Test

 

이클립스 프로젝트 Properties의 Project Facets에서 Dynamic Web Module의 버젼을 3.0에서 2.5로 변경으로 해결함

 

'Progamming' 카테고리의 다른 글

Java 웹서비스 1 준비  (0) 2012.11.22

 

-jbossws-cxf-3.4.0.GA 다운로드(http://www.jboss.org/jbossws/downloads)

-Apache-Ant-1.8.4 다운로드(http://ant.apache.org/)

-jboss 5.1.0

 

1.압축을 푼jbossws-cxf-3.4.0.GA\jbossws-cxf-bin-dist 폴더에서 ant.properties.example파일을 ant.properties 로 바꾼다.

 

2. ant.properties 수정

-jboss510.home 수정
# A sample ant properties file
#

# Optional JBoss Home
jboss501.home=/home/opalka/svn/jbossas/tags/JBoss_5_0_1_GA/build/output/jboss-5.0.1.GA
jboss510.home=C:/jboss-5.1.0.GA
jboss600.home=/dati/jboss-6.0.0.CR1/build/target/jboss-6.0.0.20101110-CR1
jboss601.home=/home/opalka/svn/jbossas/trunk/build/output/jboss-6.0.0-SNAPSHOT

# The JBoss server under test. This can be [jboss501|jboss510|jboss600|jboss601]
jbossws.integration.target=jboss510

# The JBoss settings
jboss.server.instance=default
jboss.bind.address=localhost

# JBoss JMX invoker authentication
#jmx.authentication.username=admin
#jmx.authentication.password=admin

# Java Compiler options
javac.debug=yes
javac.deprecation=no
javac.fail.onerror=yes
javac.verbose=no

3.C:\jbossws-cxf-3.4.0.GA\jbossws-cxf-bin-dist 폴더로 이동하여 ant deploy-jboss510 실행.


 

 

 

 

 

 

1.프로그램설치

-JDK 1.6 설치

-JBoss 5.1.0.GA-jdk6 (http://sourceforge.net/projects/jboss/files/JBoss/JBoss-5.1.0.GA/jboss-5.1.0.GA-jdk6.zip)

-EJBCA 4.0.12(http://sourceforge.net/projects/ejbca/files/ejbca4/ejbca_4_0_12/ejbca_4_0_12.zip)

 

 

--EJBCA_HOME/lib/bc*.jar 파일을 JBOSS_HOME/server/default/lib 폴더에 복사한다.

(If you are using Oracle's JDK and JBoss 5.1.x you need to copy EJBCA_HOME/lib/bc*.jar to JBOSS_HOME/server/default/lib/. Remember this when it's time for upgrades! This is a bug tracked by JBoss as JBAS-7882. OpenJDK works just fine though, such as the OpenJDK distributed with RedHat, Ubuntu, Debian etc.

The same bug is present on JBoss 6.0, but the workaround is different, the same workaround as for JBoss 5.1 does not work with JBoss 6. The only way to work around this with Oracle JDK and JBoss 6 is to copy ejbca/lib/bc*.jar to $JAVA_HOME/jre/lib/ext, and to remove lib/bc*.jar from the deployed ejbca.ear file. See the JBAS-7882 issue for more information.)

 

 

2.EJBCA 설정

-ejbca.properties 수정

  appserver.home=/opt/jboss-5.1.0

-ejbca폴더에서 ant bootstrap

-jboss 시작

-ant install

-ant deploy

-jboss 재시작

 

 

 

 

'Progamming > Java' 카테고리의 다른 글

RMI 정리중  (0) 2012.05.10

1.SMTP 서비스 설치

 - 서버관리자>역할에서 IIS서비스 설치

 -  서버관리자>기능에서 SMTP서버 설치

2.IIS6.0 관리자

 - SMTP가상서버 새로만들기 및 설정

3.테스트

 - telnet 127.0.0.1 25

 - helo server

 - mail from:mail@mail.co.kr

 - rcpt to:mail@mail.co.kr

 - data

 - 메세지

 - .

 

'Progamming > 기타' 카테고리의 다른 글

Git에서 변경된 파일 다운로드  (0) 2020.04.20

RMI 정리중

Progamming/Java2012. 5. 10. 11:56

 

그림 출처: http://java.sun.com/docs/books/tutorial/rmi/overview.html

 

 

RMI(Remote Method Invocation)

 - 네트웍상에 있는 원격컴퓨터의 객체의 메소드를 호출하는 JAVA의 분산처리 방법

 

SERVER
  -원격인터페이스, 구현클래스, 서버프로그램, Stub

Stup 파일 생성
 -rmic -classpath . -d . RmiServicempl

 -rmic -classpath . -d . test.RmiServicempl

 

rmiregistry 등록 
 -start rmiregistry 1099  (기본 포트1099)
 

서버실행
java -classpath /opt/apache-tomcat-5.26/webapps/arcotweb/WEB-INF/classes/  -Djava.rmi.server.codebase=file:/opt/apache-tomcat-5.5.26/webapps/arcotweb/WEB-INF/classes/ -Djava.security.policy=server.policy  RmiServer

 

Client
 -원격인터페이스, 클라이언트프로그램, Stub

 

*문제해결 및 참고

-http://blog.naver.com/eunicon?Redirect=Log&logNo=100043860463

-http://blog.naver.com/ypark197?Redirect=Log&logNo=90034481566

-http://cafe.naver.com/sungwookhome/293

-RMI 사용에 의한 동적인 코드의 다운로드(codeb.pdf

 


'Progamming > Java' 카테고리의 다른 글

EJBCA 설치 테스트  (0) 2012.11.14