【发布时间】:2018-01-04 05:29:09
【问题描述】:
我正在尝试通过针对 https://aesencryption.net 测试我的代码来学习 AES。我之前在Base64.encodeBase64String 和Base64.decodeBase64 // encode/decode Base64 中有一个错误。所以我以某种方式操纵 Base64 来解决错误。我认为,现在在我的应用程序中,文本已正确加密和解密。但是当我尝试加密或解密相同的文本服务器端(在 aesencryption.net)时,该站点无法解密我的加密字符串。请帮忙。
以下是我的代码:
public class MainActivity extends AppCompatActivity {
static final String TAG = "SymmetricAlgorithmAES";
private static SecretKeySpec secretKey ;
private static byte[] key ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Original text
// {"type":"Success","httpCode":"200","code":"200","message":{"pin":"11111"},"extra":""}
String theTestText = "hi";
TextView tvorig = (TextView)findViewById(R.id.tvorig);
tvorig.setText("\n[ORIGINAL]:\n" + theTestText + "\n");
final String strPssword = "android";
setKey(strPssword);
// Encode the original data with AES
byte[] encodedBytes = null;
try {
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE,secretKey);
encodedBytes = c.doFinal(theTestText.getBytes());
} catch (Exception e) {
Log.e(TAG, "AES encryption error");
}
TextView tvencoded = (TextView)findViewById(R.id.tvencoded);
tvencoded.setText("[ENCODED]:\n" +
Base64.encodeToString(encodedBytes, Base64.DEFAULT) + "\n");
Log.d(TAG, Base64.encodeToString(encodedBytes, Base64.DEFAULT));
// Decode the encoded data with AES
byte[] decodedBytes = null;
try {
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE, secretKey);
decodedBytes = c.doFinal(encodedBytes);
} catch (Exception e) {
Log.e(TAG, "AES decryption error");
}
TextView tvdecoded = (TextView)findViewById(R.id.tvdecoded);
tvdecoded.setText("[DECODED]:\n" + new String(decodedBytes) + "\n");
}
public static void setKey(String myKey){
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
System.out.println(key.length);
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
System.out.println(key.length);
System.out.println(new String(key,"UTF-8"));
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
提前致谢。
【问题讨论】:
-
AES 有不同的加密模式,包括“salted”模式。在将网站克隆到应用程序之前,您必须知道网站使用的是什么模式。
-
我正在尝试从aesencryption.net/#Java-aes-encryption-example 解密相同的代码。我也无法解密或加密。
-
AES 是一种分组密码,可以有different modes of operation。因此,如果您的网站(我假设是 PHP)使用一种操作模式,而您的应用程序使用另一种操作模式,您将获得不同的结果。除此之外,AES 结果取决于您使用的character encoding。确保两端相同。
-
@Pyromonk 感谢您抽出宝贵时间。这个案例实际上是在我的脑海中。但问题是,aes 网站本身已经给出了 java 中的代码和在线检查方式。在我的代码中,我也有一些小东西被操纵,因为我没有改变模式,所以我不确定它们是否会在网站上产生影响。因此,在应用程序中,我可以轻松地加密或解密字符串。但是当我使用该加密字符串并在 aes 网站中运行时,我无法对其进行解密。
-
确保以下情况成立并运行另一个测试: 1)您加密的字符串仅包含 ANSI 字符(A-Z、a-z、_、-、0-9 等); 2)“加密密钥”在这两种情况下都是空白的; 3) 在这两种情况下,块大小都是 256 位。
标签: java php android android-studio aes