public static String encryptStringToBase64(String messageString) {
byte[] messageBytes = messageString.getBytes("UTF-8");
byte[] encrypted = convert(1, messageBytes);
return Base64.encodeBytes(encrypted);
}
private static byte[] convert(int mode, byte[] messageBytes) {
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
sha256.update("abcdefgh".getBytes("UTF-8"));
byte[] keyBytes = sha256.digest();
byte[] hash = Arrays.copyOfRange(keyBytes, 0, 16);
SecretKeySpec keySpec = new SecretKeySpec(hash, "AES");
byte[] ivBytes = new byte[16];
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(mode, keySpec, ivSpec);
return cipher.doFinal(messageBytes);
}
以上是java中用于加密的逻辑,尝试使用以下加密技术 https://gist.github.com/m1entus/f70d4d1465b90d9ee024 https://github.com/krzyzanowskim/CryptoSwift 但是我无法在java和amp;中生成相同的加密字符串。 iOS版。有什么方法可以在iOS中重现相同的数据。
Swift 3.0代码
import CryptoSwift
let ram = "aaaa"
let pas = "abbbb"
let usernameutf8data = ram.data(using: String.Encoding.utf8)
let passwordutf8data = pas.data(using: String.Encoding.utf8)
let copyRight = "abcdefgh"
let copyRightUtf8 = copyRight.data(using: .utf8)
let hash = copyRightUtf8?.sha256()
let key: Array<UInt8> = Array(hash!.bytes[0..<16])
let iv: Array<UInt8> = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]//AES.randomIV(AES.blockSize)
let encrypted = try AES(key:key , iv: iv, blockMode: .CBC, padding: PKCS7()).encrypt(usernameutf8data!)
let encryptedpas = try AES(key:key , iv: iv, blockMode: .CBC, padding: PKCS7()).encrypt(passwordutf8data!)
答案 0 :(得分:2)
Base64EncodedString:
func encryptStringToBaseSixtyFour(value : String) -> String {
let data = value.data(using: .utf8)
return data?.base64EncodedString()
}
AES加密字符串
func aesEncrypt(value: String, key: String, iv: String) throws -> String {
let data = value.data(using: .utf8)!
let encrypted = try! AES(key: key, iv: iv, blockMode: .CBC, padding: PKCS7()).encrypt([UInt8](data))
let encryptedData = Data(encrypted)
return encryptedData.base64EncodedString()
}
AES解密值
func aesDecrypt(encryptedString: String,key: String, iv: String) throws -> String {
let data = Data(base64Encoded: encryptedString)!
let decrypted = try! AES(key: key, iv: iv, blockMode: .CBC, padding: PKCS7()).decrypt([UInt8](data))
let decryptedData = Data(decrypted)
return String(bytes: decryptedData.bytes, encoding: .utf8) ?? "Could not decrypt"
}