我正在为我的 iPhone 应用程序使用 Objective C 中的加密类,但我正在努力从我的 android 应用程序中获得在 JAVA 中工作的相同功能。我的加密代码如下:
NSString * _secret = @"password";
NSString * _key = @"1428324560542678";
StringEncryption *crypto = [[StringEncryption alloc] init];
NSData *_secretData = [_secret dataUsingEncoding:NSUTF8StringEncoding];
CCOptions padding = kCCOptionPKCS7Padding;
NSData *encryptedData = [crypto encrypt:_secretData key:[_key dataUsingEncoding:NSUTF8StringEncoding] padding:&padding];
我试图在 JAVA 中复制它,但是当我对相同的数据进行编码时,我得到了一个不同的字符串。所以我做错了什么,但我无法弄清楚。这是我的 JAVA 代码:
byte[] key = "1428324560542678".getBytes();
Cipher c = null;
try {
c = Cipher.getInstance("AES/ECB/PKCS7Padding");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SecretKeySpec k = new SecretKeySpec(key, "AES");
try {
c.init(Cipher.ENCRYPT_MODE, k);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
EditText tv1passwordText = (EditText) findViewById(R.id.password);
String password = URLEncoder.encode(tv1passwordText.getText().toString(), "UTF-8");
byte[] encryptedData = c.doFinal( password.getBytes());
谁能看到我哪里出错了?
根据下面的评论,我添加了 getBytes 但生成的字符串仍然不同:
byte[] key = null;
try {
key = "1428324560542678".getBytes("UTF-8");
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Cipher c = null;
try {
c = Cipher.getInstance("AES/ECB/PKCS7Padding");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SecretKeySpec k = new SecretKeySpec(key, "AES");
try {
c.init(Cipher.ENCRYPT_MODE, k);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
EditText tv1passwordText = (EditText) findViewById(R.id.password);
byte[] password = tv1passwordText.getText().toString().getBytes("UTF-8");
byte[] encryptedData = c.doFinal(password);