再试试 public void test () throws Exception {
Key key = getKey(); //生成密钥 String data = "Hello!"; System.out.println("before encrypt----" + data);
byte[] encrypted = doEncrypt(key, data.getBytes()); //加密
String str = "";
for (int i = 0, j = 0; i < encrypted.length; i++) {
if (encrypted[i] < 0)
j = encrypted[i] + 256;
else
j = encrypted[i];
str += convertToStr(j);
} System.out.println("encrypted---" + str); byte[] decrypted = doDecrypt(key, encrypted); //解密
System.out.println("decrypted---" + new String(decrypted));
} byte[] doEncrypt (Key key, byte[] in) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(in);
return result;
} byte[] doDecrypt (Key key, byte[] in) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] result = cipher.doFinal(in);
return result;
} public Key getKey () throws Exception {
KeyGenerator kg = KeyGenerator.getInstance("DES");
Key key = kg.generateKey();
return key;
} private static String convertToStr(int c) {
String result = String.valueOf(c);
switch (result.length()) {
case 1:
result = "00" + result;
break;
case 2:
result = "0" + result;
break;
case 3:
result = result;
break;
default:
result = result.substring(0, 3);
}
return result;
} public static void main (String[] args) throws Exception {
Test test = new Test();
test.test();
}
Key key = getKey(); //生成密钥 String data = "Hello!"; System.out.println("before encrypt----" + data);
byte[] encrypted = doEncrypt(key, data.getBytes()); //加密
String str = "";
for (int i = 0, j = 0; i < encrypted.length; i++) {
if (encrypted[i] < 0)
j = encrypted[i] + 256;
else
j = encrypted[i];
str += convertToStr(j);
} System.out.println("encrypted---" + str); byte[] decrypted = doDecrypt(key, encrypted); //解密
System.out.println("decrypted---" + new String(decrypted));
} byte[] doEncrypt (Key key, byte[] in) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(in);
return result;
} byte[] doDecrypt (Key key, byte[] in) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] result = cipher.doFinal(in);
return result;
} public Key getKey () throws Exception {
KeyGenerator kg = KeyGenerator.getInstance("DES");
Key key = kg.generateKey();
return key;
} private static String convertToStr(int c) {
String result = String.valueOf(c);
switch (result.length()) {
case 1:
result = "00" + result;
break;
case 2:
result = "0" + result;
break;
case 3:
result = result;
break;
default:
result = result.substring(0, 3);
}
return result;
} public static void main (String[] args) throws Exception {
Test test = new Test();
test.test();
}
的确不错!