我正在尝试实现一个接收字符串并返回 CAST-256 中字符串的编码值的函数。以下代码是我按照 BoncyCastle 官方网页(http://www.bouncycastle.org/specifications.html,第 4.1 点)上的示例实现的。
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.engines.CAST6Engine;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
public class Test {
static{
Security.addProvider(new BouncyCastleProvider());
}
public static final String UTF8 = "utf-8";
public static final String KEY = "CLp4j13gADa9AmRsqsXGJ";
public static byte[] encrypt(String inputString) throws UnsupportedEncodingException {
final BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CAST6Engine());
byte[] key = KEY.getBytes(UTF8);
byte[] input = inputString.getBytes(UTF8);
cipher.init(true, new KeyParameter(key));
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int outputLen = cipher.processBytes(input, 0, input.length, cipherText, 0);
try {
cipher.doFinal(cipherText, outputLen);
} catch (CryptoException ce) {
System.err.println(ce);
System.exit(1);
}
return cipherText;
}
public static void main(String[] args) throws UnsupportedEncodingException {
final String toEncrypt = "hola";
final String encrypted = new String(Base64.encode(test(toEncrypt)),UTF8);
System.out.println(encrypted);
}
}
但是,当我运行我的代码时,我得到了
QUrYzMVlbx3OK6IKXWq1ng==
如果你hola
用相同的密钥在 CAST-256 中编码(如果你想要http://www.tools4noobs.com/online_tools/encrypt/试试这里)我应该得到
w5nZSYEyA8HuPL5V0J29Yg==
.
怎么了?为什么我得到一个错误的加密字符串?
我厌倦了在互联网上找到它并没有找到答案。