【发布时间】:2018-05-10 20:47:47
【问题描述】:
您好,我正在使用 openSSL 命令来加密和解密我的消息。现在我希望将此命令转换为 java 代码,我尝试了网络上提供的不同解决方案,但没有一个代码与结果匹配。
这是我在 cmets 中的低调的 OpenSSL 命令:
key="FB4FF1BA6F1FCC1A11B8B3910342CBD3A2BEAEB8F52E8910D9B25C0C96280EEA"
# Getting 16 digits from the iv.txt file and putting it into the bin
head -c 16 iv.txt > iv.bin
# Converting iv.bin text into the HEXA value
iv=`xxd -l 16 -p iv.bin`
# encrypt without "-a"
openssl enc -aes-256-cbc -K $key -iv $iv -in plainKey.txt -out encryptedKey.bin
# printing encrypted results in base64 format this need to be matched with my java code.
echo "<enc>"`cat encryptedKey.bin | base64`"</enc>"
这是我在 Java 中所做的:
注意:这个来自堆栈溢出的代码接受了稍作改动的答案我也尝试了其他一些代码,但这里不能全部提及。
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class Test {
public static void main(String[] args) {
try {
runEncryption();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void runEncryption() throws Exception
{
//String to be encrypted
String plainText = "abcd@1234\n";
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// IV text
String iv = "C837E1B6C3D3A7E28F47719DE0C182C9";
// getting 16 characters of iv text
iv = iv.substring(0,16);
// Value of key
String key = "FB4FF1BA6F1FCC1A11B8B3910342CBD3A2BEAEB8F52E8910D9B25C0C96280EEA";
// Logic for converting 16 Digits of IV into HEX
StringBuffer hexString = new StringBuffer();
for (int i=0;i<iv.getBytes().length;i++) {
String hex=Integer.toHexString(0xff & iv.getBytes()[i]);
if(hex.length()==1) hexString.append('0');
hexString.append(hex);
}
// Seems something wrong here because if i am passing all the bytes to keySpe like key.getBytes() it is producing exception so i am passing 16 bytes as previous code was doing in SO
SecretKeySpec keySpec = new SecretKeySpec(hexToBytes(key), 0, 16, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(hexToBytes(hexString.toString()));
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));
String encryptedBase64 = new String(DatatypeConverter.printBase64Binary(encrypted));
System.out.println("");
System.out.println("Encrypted base64 = " + encryptedBase64);
}
private static byte[] hexToBytes(String s)
{
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2)
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
return data;
}
}
我正在使用 openSSL 命令生成密钥和 iv
openssl enc -aes-256-cbc -k secret -P -md sha1
这里似乎有问题,因为如果我将所有字节传递给 keySpec,比如 key.getBytes(),它会产生异常,所以我传递了 16 个字节,就像之前的代码在 SO 中所做的那样,我也在代码 cmets 中提到了这一点请就此提出建议,谢谢。
【问题讨论】:
-
可能还有其他问题,但首先让我们使用相同的参数 - 您只传递了 16 个密钥字节,您实际上是在执行 AES-128,其中 openssl 与
aes-256-cbc一起使用。下一步 - 你为什么要自己进行十六进制/字符串转换? (不是
标签: java encryption openssl cryptography encryption-symmetric