当前位置: 代码迷 >> Java相关 >> 高手帮忙看看这个解密过程有什么有关问题
  详细解决方案

高手帮忙看看这个解密过程有什么有关问题

热度:7502   发布时间:2013-02-25 21:51:29.0
高手帮忙看看这个解密过程有什么问题!
问题描述:加密功能可以实现,但是加密后的字符不能实现解密(s3为空)。请高手指点!
代码如下所示:
package service;

import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

public class EnDecryptionSimple {

/**
* @param args
*/
public static void main(String[] args) 
{
String str="hello123";
try 
{
System.out.println("Generator a Blowfish key...");
KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128);
Key key = keyGenerator.generateKey();
System.out.println("Done generatoring key.");

Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,key);//加密
byte[] s1 = str.getBytes("UTF-8");
System.out.println("s1:");
for(int i=0;i<s1.length;i++)
{
System.out.print(s1[i]+"-");
}

byte[] s2 = cipher.doFinal();
System.out.println("\ns2:");
for(int i=0;i<s2.length;i++)
{
System.out.print(s2[i]+"-");
}

cipher.init(Cipher.DECRYPT_MODE, key);//解密
byte[] tmp = cipher.doFinal(s2);
String s3 = new String(tmp);
System.out.println("\nS3:"+s3);

} catch (Exception e)
{
e.printStackTrace();
}
}

}

------解决方案--------------------------------------------------------
高手还没来。
我看看。
你的两个MODE是不是有问题。
------解决方案--------------------------------------------------------
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class Test {
private static String ALGORITHM ="DES";
public static void main(String[] args) {
String str = "hello123";
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
Key key = keyGenerator.generateKey();

SecretKey deskey = new javax.crypto.spec.SecretKeySpec (key.getEncoded() ,ALGORITHM );

Cipher cipher = Cipher.getInstance (ALGORITHM );
cipher.init (Cipher.ENCRYPT_MODE ,deskey );
byte[] s1 = str.getBytes("UTF-8");

byte[] s2 = cipher.doFinal(s1);// 加密

cipher.init(Cipher.DECRYPT_MODE, deskey);
byte[] tmp = cipher.doFinal(s2);// 解密

System.out.println("s4===="+(new String(tmp)));

} catch (Exception e) {
e.printStackTrace();
}
}
}
  相关解决方案