- 论坛徽章:
- 0
|
是这样的:小弟最近在学java加密解密方面,小弟用jdk6.0编译、运行程序都没有问题,但用netbeans5.5编译没有问题,但运行它报ArrayIndexOutOfBoundsException:1错误,源代码如下:
import java.security.*;
import javax.crypto.*;
import java.io.*;
import javax.crypto.spec.*;
import java.util.*;
import sun.misc.*;
public class Main
{
private static int ITERATIONS = 1000;
private static void usage() throws Exception
{
System.err.println("Usage: Java PBE -e|-d password text");
System.exit(1);
}
public static void main(String[] args) throws Exception
{
if(args.length != 3) usage();
System.in.read();
//Convert password to a char array.
char[] password = args[1].toCharArray() //运行程序就是这里报错。
String text = args[2];
String output = null;
if("-e".equals(args[0])) output = encrypt(password, text);
else if("-d".equals(args[0])) output = decrypt(password, text);
else usage();
System.out.println(output);
}
private static String encrypt(char[] password, String plaintext) throws Exception
{
byte[] salt = new byte[8];
Random random = new Random();
random.nextBytes(salt);
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHAAndTwofish-CBC");
SecretKey key = keyFactory.generateSecret(keySpec);
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATIONS);
Cipher cipher = CIpher.getInstance("PBEWIthSHAAndTwofish-CBC");
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
byte[] ciphertext = cipher.doFinal(plaintext.getBytes());
BASE64Encoder encoder =new BASE64Encoder();
String saltString = encoder.encode(salt);
String ciphertextString = encoder.encode(ciphertext);
return saltString+ciphertextString;
}
private static String decrypt(char[] password, String text) throws Exception
{
String salt = text.substring(0, 12);
String ciphertext = text.substring(12, text.length());
BASE64Decoder decoder = new BASE64Decoder();
byte[] saltArray = decoder.decodeBuffer(salt);
byte[] ciphertextArray = decoder.decodeBuffer(ciphertext);
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHAAndTwofish-CBC");
SecretKey key = keyFactory.generateSecret(keySpec);
PBEParameterSpec paramSpec = new PBEParameterSpec(saltArray, ITERATIONS);
Cipher cipher = Cipher.getInstance("PBEWithSHAAndTwofish-CBC");
cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
byte[] plaintextArray = cipher.doFinal(ciphertextArray);
return new String(plaintextArray);
}
}
[ 本帖最后由 yhzy 于 2007-6-25 11:11 编辑 ] |
|