JKS密码验证

下面的程序用来验证JKS的文件及密码是否正确

public static URL getStoreURL(String storePath) throws IOException
{
	URL url = null;
	// First see if this is a URL
	try
	{
		url = new URL(storePath);
	}
	catch (MalformedURLException e)
	{
		// Not a URL or a protocol without a handler so...
		// next try to locate this as file path
		File tst = new File(storePath);
		if (tst.exists() == true)
		{
			url = tst.toURL();
		} else
		{
			// not a file either, lastly try to locate this as a classpath
			// resource
			if (url == null)
			{
				ClassLoader loader = Thread.currentThread().getContextClassLoader();
				url = loader.getResource(storePath);
			}
		}
	}
	// Fail if no valid key store was located
	if (url == null)
	{
		String msg = "Failed to find url=" + storePath + " as a URL, file or resource";
		throw new MalformedURLException(msg);
	}
	return url;
}

public static KeyStore loadKeyStore(String storeType, URL storePathURL, String storePassword) throws Exception
{
	KeyStore keyStore = null;
	String provider = null;
	String providerName = null;

	if (provider != null)
	{
		keyStore = KeyStore.getInstance(storeType, provider);
	} else
		if (providerName != null)
		{
			keyStore = KeyStore.getInstance(storeType, providerName);
		} else
		{
			keyStore = KeyStore.getInstance(storeType);
		}
	if (storePathURL == null) { throw new Exception("Can not find store file for url because store url is null."); }
	// now that keystore instance created, need to load data from file
	InputStream keyStoreInputStream = null;
	try
	{
		keyStoreInputStream = storePathURL.openStream();
		// is ok for password to be null, as will just be used to check
		// integrity of store
		char[] password = storePassword != null ? storePassword.toCharArray() : null;
		keyStore.load(keyStoreInputStream, password);
	}
	finally
	{
		if (keyStoreInputStream != null)
		{
			try
			{
				keyStoreInputStream.close();
			}
			catch (IOException e)
			{
				// no op
			}
			keyStoreInputStream = null;
		}
	}
	return keyStore;
}

public static String verifyP12(String p12Path,String p12Pwd)
{
            String ret = "验证成功";
            try
            {
	URL ksURL = getStoreURL(p12Path);
                if(ksURL==null)throw new Exception(p12Path+"文件未找到");
                    
	loadKeyStore("PKCS12",ksURL,p12Pwd);
            }
            catch(Exception ex)
            {
                ret = ex.getMessage();
                ex.printStackTrace();
            }
            return ret;
}

public static String verifyJks(String jksPath,String jksPwd)
{
            String ret = "验证成功";
            try
            {
	URL ksURL = getStoreURL(jksPath);
	loadKeyStore("JKS",ksURL,jksPwd);
                
                if(ksURL==null)throw new Exception(jksPath+"文件未找到");
            }
            catch(Exception ex)
            {
                ret = ex.getMessage();
                ex.printStackTrace();
            }
            
            return ret;
}

AXIS2客户端支持TLS

只要设置下面几个环境变量就好啦;)

public static final String TRUST_STORE_PASSWORD = "javax.net.ssl.trustStorePassword";
public static final String TRUST_STORE = "javax.net.ssl.trustStore";
public static final String TRUST_STORE_TYPE = "javax.net.ssl.trustStoreType";
public static final String KEY_STORE_TYPE = "javax.net.ssl.keyStoreType";
public static final String KEY_STORE_PASSWORD = "javax.net.ssl.keyStorePassword";
public static final String KEY_STORE = "javax.net.ssl.keyStore";

keytool生成key

生成keystore及cert

#生成私钥
keytool -genkey -validity 10000 -keyalg RSA -dname "CN=neohope OU=neohope O=neohope L=Shanghai C=CN" -keystore node1.jks -alias node1 -keypass password -storepass password 
#导出证书
keytool -export -file node1.crt -keystore node1.jks -alias node1 -keypass password -storepass password 
#生成truststore
keytool -import -trustcacerts -file node1.crt -keystore trust.jks -alias node1 -keypass password -storepass password 
#查看
keytool -list -keystore node1.jks
keytool -list -keystore trust.jks

jks转p12

keytool -importkeystore -srckeystore node1.jks -srcstoretype JKS -deststoretype PKCS12 -destkeystore node1.p12 -srcstorepass password -deststorepass password

JBoss配置TLS

文件%JBOSS_HOME%\server\default\deploy\jboss-web.deployer\server.xml
增加下面陪孩子

<Connector port="8443" address="${jboss.bind.address}"
          protocol="HTTP/1.1" SSLEnabled="true" 
          maxThreads="100" strategy="ms" maxHttpHeaderSize="8192"
      	  emptySessionPath="true"
      	  scheme="https" secure="true" clientAuth="false" 
      	  disableUploadTimeout="true" 
      	  keystoreFile="${jboss.server.home.dir}/conf/node1.jks"
      	  keystorePass="passward"
      	  keyAlias="node1"
      	  sslProtocol = "TLS" />

Tomcat配置TLS

%TOMCAT_HOME%/conf/server.xml中添加以下配置即可

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
	       clientAuth="false" sslProtocol="TLS"
               keystoreFile="TOMCAT_HOME\conf\AXDS_2012_Keystore.jks"
               keystorePass="password"
	       truststoreFile="TOMCAT_HOME\conf\AXDS_2012_Truststore.jks" 
	       truststorePass="password"            
	       />

SpringAOP的两种代理方式

SpringAOP有两种代理方式:JDK动态代理和CGLIB。
如果被代理的目标对象实现了至少一个接口,则会使用JDK动态代理(该目标类型实现的所有接口都将被代理)。
如果被代理的目标对象没有实现任何接口,则会使用CGLIB代理。

所以,当你将一个JDK动态代理的对象Cast为一个Class而不是Interface的时候,就会报ClassCastException

这时,就要强制使用CGLIB代理

<aop:config proxy-target-class="true">
...
</aop:config>

或在使用@AspectJ时强制使用CGLIB代理

<aop:aspectj-autoproxy proxy-target-class="true">
    <aop:include name="bean1" />
    <aop:include name="bean2" />
    ....
</aop:aspectj-autoproxy>

VC的链接顺序

CRT库在链接new, delete, DllMain这些符号的时候,使用的是弱外链接
MFC库同样也包含了new, delete, DllMain这几个符号,而MFC库必须在CRT库之前被链接才会成功。

如果link时出现了符号冲突,做下面的设置即可
project>properties>configuration properties>linker>input
在”Additional dependency”中依次增加 Nafxcwd.lib Libcmtd.lib
在add to “ignore specific library”中依次增加Nafxcwd.lib;Libcmtd.lib

CS访问网络资源

using System.Runtime.InteropServices;
 
public class WNetHelper
{
	 [DllImport("mpr.dll", EntryPoint = "WNetAddConnection2")]
	 private static extern uint WNetAddConnection2(NetResource lpNetResource, string lpPassword, string lpUsername, uint dwFlags);
 
	 [DllImport("Mpr.dll", EntryPoint = "WNetCancelConnection2")]
	 private static extern uint WNetCancelConnection2(string lpName, uint dwFlags, bool fForce);
 
	 [StructLayout(LayoutKind.Sequential)]
	 public class NetResource
	 {
		  public int dwScope;
		  public int dwType;
		  public int dwDisplayType;
		  public int dwUsage;
		  public string lpLocalName;
		  public string lpRemoteName;
		  public string lpComment;
		  public string lpProvider;
	 }
 
	 public static uint WNetAddConnection(string username, string password, string remoteName, string localName)
	 {
		  NetResource netResource = new NetResource();
 
		  netResource.dwScope = 2;
		  netResource.dwType = 1;
		  netResource.dwDisplayType = 3;
		  netResource.dwUsage = 1;
		  netResource.lpLocalName = localName;
		  netResource.lpRemoteName = remoteName.TrimEnd('\\');
		  uint result = WNetAddConnection2(netResource, password, username, 0);
 
		  return result;
	 }
 
	 public static uint WNetCancelConnection(string name, uint flags, bool force)
	 {
		  uint nret = WNetCancelConnection2(name, flags, force);
		  return nret;
	 }
}

VC服务程序调用远程资源

当VC服务程序调用远程资源时,经常返回路径不存在等问题
这是因为Windows中,服务程序以System用户登录,而不是桌面用户登录
这样就导致,虽然桌面程序已经映射网络资源,但System用户仍无法访问的问题
为了可以访问远程资源,可以调用API:WNetAddConnection2

BOOL AcessNetworkDrtive(CString szDevice,CString szDeviceName,CString szUsername,CString szPassword)
{
	DWORD dwRetVal;
	NETRESOURCE nr;

	memset(&nr, 0, sizeof (NETRESOURCE));
	nr.dwType = RESOURCETYPE_ANY;
	nr.lpLocalName = strDevice.GetBuffer(szDevice.GetLength());
	nr.lpRemoteName = szDeviceName.GetBuffer(szDeviceName.GetLength());
	nr.lpProvider = NULL;

	dwRetVal = WNetAddConnection2(&nr, szUsername, szUsername, CONNECT_UPDATE_PROFILE);

	if (dwRetVal != NO_ERROR)
	{
		CString cError;
		cError.Format(TEXT("[ERROR]WNetAddConnection2 Failed: %u\n"), dwRetVal);
		LogEvent(cError,TEXT("With remote name "),nr.lpRemoteName);
		return dwRetVal;
	}

	return 	dwRetVal;
}

C#深度拷贝

如果类实现了序列化,那么先序列化再反序列化一下,
就得到了一个深度拷贝的对象啦

public static T DeepClone<T>(T obj)
{
    using (var ms = new MemoryStream())
    {
        var formatter = new BinaryFormatter();
        formatter.Serialize(ms, obj);
        ms.Position = 0;
        return (T) formatter.Deserialize(ms);
    }
}