加密时出现问题导致错误:
javax.crypto.IllegalBlockSizeException: data not block size aligned
at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(Unknown Source)
at javax.crypto.Cipher.doFinal(Cipher.java:2086)
at com.lcp.sso.logic.SsoCipher.encode(SsoCipher.java:89)
对象的构造函数:
public MyCipher() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException {
Security.addProvider(new BouncyCastleProvider());
KeyGenerator keyGen = KeyGenerator.getInstance("DESede", "BC");
keyGen.init(new SecureRandom());
SecretKey keySpec = keyGen.generateKey();
this.sharedKey = keySpec.getEncoded().toString();
this.encrypter = Cipher.getInstance("DESede/ECB/Nopadding", "BC");
this.encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
this.decrypter = Cipher.getInstance("DESede/ECB/Nopadding", "BC");
this.decrypter.init(Cipher.DECRYPT_MODE, keySpec);
}
发生错误的方法:
public String encode(String arg_text) throws IllegalBlockSizeException, BadPaddingException {
byte[] encrypt = arg_text.getBytes();
if(encrypt.length % 8 != 0){ //not a multiple of 8
//create a new array with a size which is a multiple of 8
byte[] padded = new byte[encrypt.length + 8 - (encrypt.length % 8)];
//copy the old array into it
System.arraycopy(encrypt, 0, padded, 0, encrypt.length);
encrypt = padded;
}
byte[] b = Base64.encodeBase64URLSafe(encrypt);
return Base64.encodeBase64String(encrypter.doFinal(b));
}
在那里调用最后一个方法时会发生错误。我发誓我正在通过对字节数组进行空填充以确保它是 8 的倍数,从而将其设置为正确的块大小。我只是不知道出了什么问题!
我正在使用:
Eclipse 版本:Juno Service Release 1
服务器:本地主机上的 Tomcat v7.0 服务器(特别是 7.0.32)
---编辑---
程序还没有工作,(编辑:是的!Muahahahaha!)但是这个问题已经解决了。
对象的构造函数:
public MyCipher() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, InvalidParameterSpecException, InvalidAlgorithmParameterException {
Security.addProvider(new BouncyCastleProvider());
KeyGenerator keyGen = KeyGenerator.getInstance("DES", "BC");
keyGen.init(new SecureRandom());
SecretKey keySpec = keyGen.generateKey();
this.sharedKey = new String( Base64.encodeBase64URLSafe( keySpec.getEncoded() ) );
this.encrypter = Cipher.getInstance("DES/CBC/PKCS5Padding", "BC");
this.encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
AlgorithmParameters params = this.encrypter.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
IvParameterSpec ivSpec = new IvParameterSpec(iv);
this.sharedIV = new String( Base64.encodeBase64URLSafe( iv ) );
this.decrypter = Cipher.getInstance("DES/CBC/PKCS5Padding", "BC");
this.decrypter.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
}
加密方法是:
public String encode(String arg_text) throws IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] encrypt = arg_text.getBytes();
return new String( Base64.encodeBase64URLSafe(encrypter.doFinal(encrypt)), "US-ASCII");
}
它现在可以很好地加密和解密。非常感谢你。