我有一个预先编写的代码,用于对给定的纯文本进行加密,反之亦然。无法更改Base64解码器中的密码密钥
该类有3种方法,其中可以分别使用2种方法进行加密和解密。
public class SqlCipherUtil {
private Cipher ecipher;
private Cipher dcipher;
public String encryptString(String pStrPlainText) {
try {
generateKey();
byte[] utf8 = pStrPlainText.getBytes("UTF8");
byte[] enc = this.ecipher.doFinal(utf8);
return new BASE64Encoder().encode(enc);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String decryptString(String pStrCipherText){
try {
generateKey();
byte[] dec = new BASE64Decoder().decodeBuffer(pStrCipherText);
byte[] utf8 = this.dcipher.doFinal(dec);
return new String(utf8, "UTF8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* This method is used to generate the encrypted key.
*/
private void generateKey() {
try {
byte[] decodedStr = new BASE64Decoder().decodeBuffer("rA/LUdBA/hA=");
SecretKey key = new SecretKeySpec(decodedStr, "DES");
this.ecipher = Cipher.getInstance("DES");
this.dcipher = Cipher.getInstance("DES");
this.ecipher.init(1, key);
this.dcipher.init(2, key);
} catch (Exception e) {
e.printStackTrace();
}
}
}
键存在于类的不能在线路byte[] decodedStr = new BASE64Decoder().decodeBuffer("rA/LUdBA/hA=");
, 改为任何其他键 和它给一个异常。
java.security.InvalidKeyException: Invalid key length: 9 bytes
at com.sun.crypto.provider.DESCipher.engineGetKeySize(DashoA13*..)
at javax.crypto.Cipher.b(DashoA13*..)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
我尝试了下面的代码,我正好在数组中获得8个字节。
public static void main(String[] args) throws IOException {
byte[] decodedStr = new BASE64Decoder().decodeBuffer("rA/LUdBA/hA=");
for(byte b : decodedStr){
System.out.print(b);
System.out.print(" ");
}
}
}
关键的任何其他组合将使字节数组的大小超过8比7
什么是背后得到字节数组的大小8的概念少了?
应该如何使用自定义组合键或我们的自定义生成的键?
请回答这两个问题。
在初始化代码对我的作品......你确定吗?你已经准备好了那些代码? –
如果密钥只是“rA/LUdBA/hA =”,代码对我来说工作正常。 如果我们改变密钥,我会得到一个异常。 尝试一下自己,将密钥更改为不同的密钥, 在主程序中尝试调用 新的SqlCipherUtil()。encryptString(“jon-skeet”); 你会得到一个例外。 – bali208