我从事一个使用 AES 通过 TCP 加密数据的项目,但我遇到了一个没有任何答案的问题。
我尝试在 Eclipse 中测试我的软件,但没有发生错误。但是,当我将它编译为 JAR 文件时,加密会发生变化。
这是我的消息来源:
private final static String SECRETE_KEY = "xxxxxxxxxxxxxxxx";
private final static String IV = "0000000000000000";
/**
* Encrypt the message with the secrete key in parameter
*/
public static String encrypt(String message) throws Exception {
// The input length to encrypt should be a multiple of 16
while (message.length() % 16 != 0) {
message += " ";
}
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(SECRETE_KEY.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
byte[] cipherByteArray = cipher.doFinal(message.getBytes("UTF-8"));
String cipherMsg = "";
for (int i = 0; i < cipherByteArray.length; i++) {
cipherMsg += (char) cipherByteArray[i];
}
return cipherMsg;
}
/**
* Decrypt the message with the secrete key in parameter
*/
public static String decrypt(String cipherMsg) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(SECRETE_KEY.getBytes("UTF-8"), "AES");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
byte[] cipherByteArray = new byte[cipherMsg.length()];
for (int i = 0; i < cipherMsg.length(); i++) {
cipherByteArray[i] = (byte) cipherMsg.charAt(i);
}
return new String(cipher.doFinal(cipherByteArray));
}
我认为这是一个编码问题,并且全部设置为 UTF-8(源和消息),但我在另一个 Eclipse 项目中将此 JAR 文件用作库,并且 AES 可以正常工作。
有人有线索吗 ?
编辑 1:我使用 ANT 构建
<project default="all" basedir="." name="JAR - MyProject">
<property name="jarFile" value="MyJar.jar" />
<path id="libraries">
<fileset dir="lib/">
<include name="*.jar"/>
</fileset>
</path>
<pathconvert property="lib.classpath" pathsep=" ">
<path refid="libraries"/>
<flattenmapper/>
</pathconvert>
<target name="clean">
<delete file="dist/${jarFile}"/>
<delete dir="build" />
<mkdir dir="dist" />
<mkdir dir="build" />
</target>
<target name="buildJar" depends="clean">
<mkdir dir="build/classes" />
<copy todir="build/classes">
<fileset dir="classes" includes="**/*.*"/>
</copy>
<jar jarfile="dist/${jarFile}" basedir="build/classes" compress="true" excludes="**/*.java">
<manifest>
<attribute name="Main-Class" value="MyMainClass" />
<attribute name="Class-Path" value="${lib.classpath}" />
</manifest>
</jar>
</target>
<target name="all" depends="buildJar" />
</project>