[英]I need to decrypt AES-256 text from java to ios swift
我有一個鹽,iv 和密碼,分別是 hash 使用md5
。
例如: let md5Text = md5("password")
。 鹽和 IV 相同。
然后將使用 md5 salt 和密碼生成密鑰。 此生成的密鑰使用HMACSHA1
算法創建,提供 1024 次迭代(輪)和 256 的密鑰長度。
然后使用生成的密鑰和md5
iv 來加密純文本。
我可以在我的終端(iOS)生成密鑰並加密和解密。 但是當我從 java 解密加密文本時,我不會得到預期的結果。
誰能幫我轉換 JAVA 結束邏輯以在 iOS swift 4.3 中實現它以實現 aes 256 加密?
請在下面找到示例 java 代碼:
public class MD5
{
public static String getHash1(String s) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++) {
String hex = Integer.toHexString(0xFF & messageDigest[i]);
while (hex.length() < 2) {
hex = "0" + hex;
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public static String encryptedToAes(String password, String salt, int iterations, int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException {
char[] chars = password.toCharArray();
PBEKeySpec spec = new PBEKeySpec(chars, salt.getBytes(), 1024, 256);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecreteKey tmp = skf.generateSecrete(spec)
SecreteKey secrete = new SecreteKeySpec(tmp.getEncoded(), "AES");
byte[] iv_bytes = toBin(iv);
IvParameterSpec ivspec = new IvParameterSpec(iv_bytes);
Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret, ivspec);
byte[] encryptedText = cipher.doFinal(plainText.getBytes())
return toHex(encryptedText);
}
// Converts byte array to a hexadecimal string
private static byte[] toHex(String str) {
int length = str.length() / 2;
byte[] buffer = new byte[length];
for (int i = 0; i < array.length; i++) {
buffer[i] = (byte) Integer.parseInt(str.subString(i*2, i*2+2), 16);
}
return buffer;
}
private static String toBin(byte[] array) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; i++) {
sb.append(Integer.toString((array[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
private string pass = getHash1("Password")
private string salt = getHash1("Salt")
private string iv = getHash1("IV")
encryptedToAes(pass, salt, 1024, 256)
PlainText = "TEST"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.