关于string转byte[]的问题

gamebus 2003-04-09 03:57:42
String estr="test";
byte[] temp=estr.getBytes();
String temp2=new String(temp);
System.out.println(temp+" : "+temp2.getBytes());

为什么会不相等啊
...全文
3178 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
gamebus 2003-04-09
  • 打赏
  • 举报
回复
加密解密时,如果我将加密的明文转成String,在由String转成byte,就会有时出错有时正确,
出错javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA6275)
at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA6275)
at javax.crypto.Cipher.doFinal(DashoA6275)
而byte[] clearByte=c1.doFinal(crypteByte); 里crypteByte替换成直接加密后的
cipherByte就没出现这个错误

public static void main(String args[])
{
try
{
String estr="test";
test tt=new test();
tt.run();
}
catch(Exception e){
e.printStackTrace();
}
}
public void run() {
//添加新安全算法,如果用JCE就要把它添加进去
Security.addProvider(new com.sun.crypto.provider.SunJCE());
String Algorithm="DES"; //定义 加密算法,可用 DES,DESede,Blowfish
String myinfo="你好";
try {
//生成密钥
KeyGenerator keygen = KeyGenerator.getInstance(Algorithm);
SecretKey deskey = keygen.generateKey();
System.out.println(deskey);
//加密

System.out.println("加密前的信息:"+myinfo);
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE,deskey);
byte[] cipherByte=c1.doFinal(myinfo.getBytes());
String estr=new String(cipherByte);
System.out.println("加密后的串:"+estr);
//解密
byte[] crypteByte=estr.getBytes();
System.out.println("解密后的串:"+new String(crypteByte));
c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE,deskey);
byte[] clearByte=c1.doFinal(crypteByte);

System.out.println("解密后的信息:"+(new String(clearByte)));

}
catch (java.security.NoSuchAlgorithmException e1) {e1.printStackTrace();}
catch (javax.crypto.NoSuchPaddingException e2) {e2.printStackTrace();}
catch (java.lang.Exception e3) {e3.printStackTrace();}
}
希偌 2003-04-09
  • 打赏
  • 举报
回复
你得到的是temp和temp2的地址,当然不相同啦

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧