[LDAP SSL]Connection
public LDAPConnection getSSLConnection()throws AppException{
LDAPConnection ldapConn = null;
try{
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
netscape.ldap.factory.JSSESocketFactory jssesocket = new netscape.ldap.factory.JSSESocketFactory(null);
ldapConn = new LDAPConnection(jssesocket);
ldapConn.connect(conf.getString("com.ldap.connect.ip.first"), conf.getInt("com.ldap.connect.port"));
ldapConn.authenticate(conf.getString("com.ldap.connect.id"), conf.getString("com.ldap.connect.pw"));
if(ldapConn == null || !ldapConn.isConnected()){
ldapConn = new LDAPConnection();
ldapConn.connect(conf.getString("com.ldap.connect.ip.second"), conf.getInt("com.ldap.connect.port"));
ldapConn.authenticate(conf.getString("com.ldap.connect.id"), conf.getString("com.ldap.connect.pw"));
}
}catch(Exception ex1){
Log.error("ERROR", this, "LDAPQueryRunner.getConnection() Exception_1" + ex1);
try{
ldapConn = new LDAPConnection();
ldapConn.connect(conf.getString("com.ldap.connect.ip.second"), conf.getInt("com.ldap.connect.port"));
ldapConn.authenticate(conf.getString("com.ldap.connect.id"), conf.getString("com.ldap.connect.pw"));
if(ldapConn == null || !ldapConn.isConnected()){
ldapConn = new LDAPConnection();
ldapConn.connect(conf.getString("com.ldap.connect.ip.first"), conf.getInt("com.ldap.connect.port"));
ldapConn.authenticate(conf.getString("com.ldap.connect.id"), conf.getString("com.ldap.connect.pw"));
}
}catch(Exception ex2){
Log.error("ERROR", this, "LDAPUserSearch.getConnection() Exception" + ex2);
ex2.printStackTrace();
throw new AppException("LDAPUserSearch.getConnection() Exception", ex2);
}
}
return ldapConn;
}
'Progamming > LDAP' 카테고리의 다른 글
[LDAP SSL] TEST (0) | 2012.12.04 |
---|---|
[LDAP SSL]InstallCert (0) | 2012.12.04 |
[LDAP SSL]인증서 생성 (0) | 2012.12.04 |
[LDAP SSL] TEST
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 |
[LDAP SSL]InstallCert
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 |
[LDAP SSL]인증서 생성
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 |