Archive for the 'Uncategorized' Category
如何用Java进行3DES加密解密
Posted on January 5, 2008 - Filed Under Uncategorized
最近一个合作商提出使用3DES交换数据,本来他们有现成的代码,可惜只有.net版本,我们的服务器都是Linux,而且应用都是Java。于是对照他们提供的代码改了一个Java的版本出来,主要是不熟悉3DES,折腾了一天,终于搞定。
所谓3DES,就是把DES做三次,当然不是简单地DES DES DES就行了,中途有些特定的排列。这个我可不关心,呵呵,我的目的是使用它。
在网上搜索了一下3DES,找到很少资料。经过朋友介绍,找到GNU Crypto和Bouncy Castle两个Java扩充包,里面应该有3DES的实现吧。
从GNU Crypto入手,找到一个TripleDES的实现类,发现原来3DES还有一个名字叫DESede,在网上搜索TripleDES和DESede,呵呵,终于发现更多的资料了。
Java的安全API始终那么难用,先创建一个cipher看看算法在不在吧
Cipher cipher = Cipher.getInstance("DESede");
如果没有抛异常的话,就证明这个算法是有效的
突然想看看JDK有没有内置DESede,于是撇开Crypto,直接测试,发现可以正确运行。在jce.jar里面找到相关的类,JDK内置了。
于是直接用DES的代码来改&测试,最后代码变成这样
SecureRandom sr = new SecureRandom();
DESedeKeySpec dks = new DESedeKeySpec(PASSWORD_CRYPT_KEY.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
return new String(Hex.encodeHex(cipher.doFinal(str.getBytes())));
需要留意的是,要使用DESede的Spec、Factory和Cipher才行
事情还没完结,合作商给过来的除了密钥之外,还有一个IV向量。搜索了一下,发现有一个IvParameterSpec类,于是代码变成这样
SecureRandom sr = new SecureRandom();
DESedeKeySpec dks = new DESedeKeySpec(PASSWORD_CRYPT_KEY.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey securekey = keyFactory.generateSecret(dks);
IvParameterSpec iv = new IvParameterSpec(PASSWORD_IV.getBytes());
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, securekey, iv, sr);
return new [...]
如何用Java进行DES加密解密
Posted on January 5, 2008 - Filed Under Uncategorized
这篇其实是引子,直接贴代码,不多解释了
SecureRandom sr = new SecureRandom();
DESKeySpec dks = new DESKeySpec(PASSWORD_CRYPT_KEY.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
return new String(Hex.encodeHex(cipher.doFinal(str.getBytes())));
SecureRandom sr = new SecureRandom();
DESKeySpec dks = new DESKeySpec(PASSWORD_CRYPT_KEY.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
return new String(cipher.doFinal(Hex.decodeHex(str.toCharArray())));
PageCacheFilter2
Posted on December 31, 2007 - Filed Under Uncategorized
最近翻起一年多前在上一家公司写的代码,发现也有不少工具性质的类,于是整理一下都贴出来吧
/**
* 2006-5-1
* @author Sparkle
*/
public class PageCacheFilter2 implements Filter {
private Set<String> cacheUrlSet = new HashSet<String>();
private Set<String> scacheUrlSet = new HashSet<String>();
private String baseCachePath, contentType;
public void init(FilterConfig config) throws ServletException {
String cacheUrl = config.getInitParameter("cacheUrl");
if (cacheUrl != null) {
StringTokenizer tk = new StringTokenizer(cacheUrl);
while (tk.hasMoreTokens()) {
String str = tk.nextToken().trim().toLowerCase();
if (str.endsWith("?")) {
str = str.substring(0, str.length() - 1);
scacheUrlSet.add(str);
}
cacheUrlSet.add(str);
}
}
baseCachePath = [...]
ContentRewriteFilter
Posted on December 31, 2007 - Filed Under Uncategorized
最近翻起一年多前在上一家公司写的代码,发现也有不少工具性质的类,于是整理一下都贴出来吧
/**
* 2006-4-30
* @author Sparkle
*/
public abstract class ContentRewriteFilter implements Filter {
protected boolean wantRewrite(HttpServletRequest request) {
return true;
}
protected abstract String rewrite(String content,
HttpServletRequest request, HttpServletResponse response);
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest [...]
CryptUtil
Posted on December 31, 2007 - Filed Under Uncategorized
最近翻起一年多前在上一家公司写的代码,发现也有不少工具性质的类,于是整理一下都贴出来吧
/**
* 2006-6-10
* @author Sparkle
*/
public class CryptUtil {
/**
* 将一个数字转换成0-9a-zA-z的62进制
*/
public static String encodeLongToString(long i) {
if (i == 0) {
return "0";
} else if (i < 0) {
throw new IllegalArgumentException();
}
StringBuffer buffer = new StringBuffer();
while [...]
sexy Quartz
Posted on November 28, 2007 - Filed Under Uncategorized
一个系统里面经常需要做一些定时任务,比如说定时清空今日得分,或者定时清理临时文件。简单的定时任务很容易实现,用线程或者用Timer就可以了,但是始终需要自己写大量代码才能实现复杂的需求。
于是便有Quartz。不过,Quartz太久没有更新了,而且它太复杂。由于我的系统是基于Spring构建的,所以我希望能使用Spring支持的scheduling类库,可惜Spring只支持commonj和Quartz,正确来说,在Java界,并没有别的scheduling类库了,而commonj只是一个interface,没有具体的实现,似乎在Weblogic之类的里面有实现。
当然,也有另外一个选择,也是轻量级的脚本语言常用的做法,就是使用Linux的crontable,可以实现比较复杂的定时。不过,脚本语言调用数据库并不是很方便(应该说我们的团队技术累积上的问题),如果用crontable启动Java,每次启动的成本又比较高。
在评估过各种方案之后,我还是选择了使用Quartz,首先从Spring的辅助类开始入手吧。
题外话,在一个集群的环境里面(也就是多个Tomcat的环境下),定时任务应该是独立的应用,也就是不应该在每一个Tomcat里面都启动Quartz或者定时线程。另外,在Tomcat的应用里面,也是尽量不要使用线程,有可能一点点小错误就会导致整个Tomcat崩溃(其实我们还是使用很多的,呵呵)。
根据Quartz的使用行为,一个任务我们至少需要一个Job、一个JobDetail、一个Trigger(真复杂)
JobDetail jobDetail = new JobDetail("myJob", // job name
[...]
比较高效的关键字过滤代码
Posted on July 26, 2007 - Filed Under Uncategorized
public String keywordMask(String str) {
StringBuffer buffer = new StringBuffer(str);
for (String keyword : getKeyword()) {
int index = 0;
while (true) {
index = buffer.indexOf(keyword, index);
if (index < 0) {
break;
}
for (int i = 0; i < keyword.length(); i++) {
buffer.setCharAt(index + i, ‘*’);
}
}
}
return buffer.toString();
}
servlet 2.5的web.xml
Posted on March 17, 2007 - Filed Under Uncategorized
sun从来不把servlet各个版本的web.xml的规格公布一下,即使上网查找,也很难发现。倒是跟随支援的servlet容器会发布一些范例程序,好运的话,里面将会有最新版本的web.xml写法,比如说,tomcat6正式版里面有了servlet 2.5的写法,如下:
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
version="2.5">
别以为看到这里就结束了,很可惜地告诉你,这段代码是错误的。不信你尝试打开一下这个链接http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd,你会发现是no page found。
那为什么tomcat6的范例程序能够工作呢,那是因为在tomcat6的lib里面,已经存在这个文件,所以也不需要从网络上面抓取。其实你按照这个web.xml写了servlet 2.5的程序,在tomcat6里面也是可以运行的。
可是当我使用eclipse+xmlbuddy的时候,问题就出来了,因为web-app_2_5.xsd一直不能下载,xmlbuddy一直报错,并且没有语法提示功能。通过搜索,我发现了web-app_2_5.xsd的真实地址其实是http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd,而它的namespace是http://java.sun.com/xml/ns/javaee,于是代码应该改成:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
留意一下不同的部分,其实是因为sun把j2ee改名为javaee。
ps,另外附上servlet 2.4的写法
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
[...]
ruby and unicode
Posted on December 11, 2006 - Filed Under Uncategorized
unicode是ruby的痛
习惯了unicode的java转到ruby真是痛苦
也不知道同为CJK地带的ruby作者为什么不重视这个
虽然提供了jcode.rb来处理一些基本的unicode事情,但是并不完美
一下是jcode.rb的基本用法
require "jcode"
$KCODE = "u"
str.each_char
str.jlength
其实还有更简单的方法,没有必要使用jcode.rb
ruby的正则表达式可以处理unicode
我们可以利用这个来做一些简单的操作
strs = str.scan(/./mu)
strs.each
strs[0,400].join
strs.length
m就是mutilline
而u就是unicode匹配
我更倾向使用这种方法
SentenceAnalyzer
Posted on February 20, 2006 - Filed Under Uncategorized
public class SentenceAnalyzer {
private char[] interpunction = new char[] { ‘!’, ‘…’, ‘!’, ‘?’, ‘,’, ‘@’,
‘“’, ‘”’, ‘"’, ‘\”, ‘《’, ‘》’, ‘{’, ‘}’, ‘(’, ‘)’, ‘;’, ‘:’, ‘>’,
‘<’, ‘~’, ‘_’, ‘.’, ‘[', ']‘, ‘/’, ‘-’, ‘:’ };
public SentenceAnalyzer() {
interpunctionSet = new HashSet<Character>();
for (char interpunctionChar : interpunction) {
interpunctionSet.add(interpunctionChar);
}
interpunction = null;
}
private Set<Character> interpunctionSet;
public [...]