---
title: "java blowfish cbc编码解码"
author: "sam_hg"
date: "2010-07-16T17:51:48Z"
tags: []
categories: ["编程语言"]
slug: "java-blowfish-cbc"
draft: false
lastmod: "2010-07-16T18:02:22Z"
id: 714653
url: "https://sam-hg.iteye.com/blog/714653"
---

java的javax.crypto.Cipher类可以用来做blowfish-cbc算法的编解码；（关于这个类的用法很多好心人已经放在网上，我这里只记录我遇到的问题及解决方法）

我写了一段程序目的是实现php写的一段blowfish-cbc编解码算法，废话不多说了直接上代码：


```java



import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;


public class BlowfishCoder {

	private static final String KEY = "fucking_java_fucking_java_fucking_java_fucking_java_fucking_javafucking_java";
	private static final String ALGORITHM = "Blowfish";
	private static final String MODE = "Blowfish/CBC/NoPadding";

	private SecretKeySpec key = null;
	private Cipher cipherEcode = null;
	private Cipher cipherDecode = null;
	private static BlowfishCoder blowfishCoder = null;
	
	private BlowfishCoder(){}
	
	private void initKey(){
		if(null != this.key){
			return;
		}
		try{
			byte salt[] = KEY.subSequence(0, 32).toString().getBytes();
			this.key = new SecretKeySpec(salt, ALGORITHM);
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private void initCipher(int mode){
		initKey();
		try {
			Cipher cipher = Cipher.getInstance(MODE);
			byte[] iv = KEY.subSequence(32, 40).toString().getBytes();
			IvParameterSpec sr = new IvParameterSpec(iv);
			
			cipher.init(mode, this.key, sr);
			if(Cipher.DECRYPT_MODE == mode){
				this.cipherDecode = cipher;
			}
			if(Cipher.ENCRYPT_MODE == mode){
				this.cipherEcode  = cipher;
			}
		}catch (Exception e) {
			e.printStackTrace();
			
		}
		
	}
	
	private String cripherDecode(String in){
		
		try {

			String pass = in;
			
			byte[] xx = Base64.decode(pass);

			Cipher cipher = this.cipherDecode;

			byte[] encrypted = cipher.doFinal( xx );
			String id = new String(encrypted);

			return id;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private String cripherEncode(String in){       

		try {
			
			Cipher cipher = this.cipherEcode;
			
			byte[] encrypted = cipher.doFinal( in.getBytes() );

			String code = Base64.encode(encrypted);


			return code;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static void getInstance(){
		if(null == blowfishCoder){
			blowfishCoder = new BlowfishCoder();
			blowfishCoder.initCipher(Cipher.DECRYPT_MODE);
			blowfishCoder.initCipher(Cipher.ENCRYPT_MODE);
		}
	}
	
	public static String idCrypt(String text, String mode){
		getInstance();
		String retStr = null;
		if ( 0 == mode.compareTo("ENCRYPT") ){
			retStr = blowfishCoder.cripherEncode(text);
		}
		if ( 0 == mode.compareTo("DECRYPT") ){
			retStr = blowfishCoder.cripherDecode(text);
		}
		return retStr;
	}
	
	public static void main(String args[]){

		String code = idCrypt("54539405", "ENCRYPT");
		
		String id = idCrypt(code, "DECRYPT");
		System.out.println("54539405->"+code);
		System.out.println(code+"->"+id);

	}
}


```


调试的时候总是异常：
InvalidKeyException: Illegal key size
我把这段代码：

```java

KEY.subSequence(0, 32).toString().getBytes();

```

改为：

```java

KEY.subSequence(0, 8).toString().getBytes();

```

成功执行，但这并不是我想要的结果。
Google一下在国内的论坛并没有发现有人问这样的问题，old外的网站论坛上有很多人遇到这个问题，有人提出解决方法是下载jbc安装，我很兴奋，try it。
下载下来发现有两个jar包：local_policy.jar，US_export_policy.jar；
我把他们直接copy到 jre/lib/security/目录下，发现这里面已经有了，不管那么多直接替换掉。
改回代码：

```java

KEY.subSequence(0, 32).toString().getBytes();

```


然后运行，成功，结果是：

```java

54539405->jmViRJdYx7s=
jmViRJdYx7s=->54539405
```


javaeye 开博第一篇日志，小小的庆祝一下。