У меня есть код Java, где я использовал криптографию (шифрование и дешифрование).Я хочу использовать тот же процесс для быстрого кода.// мой код Java для шифрования в классе шифрования
class Crypto {
private SecretKeySpec skc;
private final static char[] hexArray = "0123456789abcdef".toCharArray();
String TAG = "TAG";
@RequiresApi(api = Build.VERSION_CODES.O)
Crypto(String token) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(("YourStrongKey" + token).getBytes("UTF-8"));
skc = new SecretKeySpec(thedigest, "AES/ECB/PKCS5Padding");
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len/2];
for(int i = 0; i < len; i+=2){
data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
}
return data;
}
public byte[] encrypt(String clear) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skc);
byte[] input = clear.getBytes("utf-8");
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
cipher.doFinal(cipherText, ctLength);
Log.d(TAG, "encrypt: ciper: "+cipher.toString());
return cipherText;
}
public byte[] decrypt(byte[] buf, int offset, int len) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skc);
byte[] dec = new byte[cipher.getOutputSize(len - offset)];
int ctLength = cipher.update(buf, offset, len - offset, dec, 0);
cipher.doFinal(dec, ctLength);
Log.d(TAG, "encrypt: dec: "+dec.toString());
return dec;
}
}
// использует основной класс активности формы Java
Crypto crypto;
String token = "Jpc3MiOiJodHRwczovL3NlY3VyZXRva2";
crypto = new Crypto(token);
JSONObject msg = new JSONObject();
msg.put("phoneData", "data1");
msg.put("countryData", "data2");
Log.d(TAG, "startHttpApiRequest: msg: "+msg);
String ss = msg.toString();
byte[] msgD = crypto.encrypt(ss);
// мой быстрый код на детской площадке
class SecretSpec {
var algorithm: String = "AES/ECB/PKCS7padding"
var key = [UInt8]()
func secretSpec(key: [UInt8], algorithm: String){
self.key = key
self.algorithm = algorithm
}
func getAlgorithm() -> String {
return self.algorithm
}
func getFormat() -> String {
return "RAW"
}
func getEncoded() -> [UInt8] {
return self.key
}
func hashCode() -> Int {
var retval: Int = 0
for i in 1...key.count-1 {
retval = retval + Int(key[i]) * Int(i)
}
if (algorithm.lowercased() == "tripledes"){
retval = retval ^ Int("desede".hashValue)
return retval
}else{
retval = retval ^ Int(algorithm.lowercased().hashValue)
return retval
}
}
}
extension String {
func aesEncrypt(key: String) -> String? {
if let keyData = key.data(using: String.Encoding.utf8),
let data = self.data(using: String.Encoding.utf8),
let cryptData = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) {
let keyLength = size_t(kCCKeySizeAES128)
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation, algoritm, options,
(keyData as NSData).bytes,keyLength,nil, (data as NSData).bytes, data.count,cryptData.mutableBytes, cryptData.length,&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
var bytes = [UInt8](repeating: 0, count: cryptData.length)
cryptData.getBytes(&bytes, length: cryptData.length)
var hexString = ""
for byte in bytes {
hexString += String(format:"%02x", UInt8(byte))
}
return hexString
}
else {
return nil
}
}
return nil
}
}
func MD5(_ string: String) -> String? {
let length = Int(CC_MD5_DIGEST_LENGTH)
var digest = [UInt8](repeating: 0, count: length)
if let d = string.data(using: String.Encoding.utf8) {
_ = d.withUnsafeBytes { (body: UnsafePointer<UInt8>) in
CC_MD5(body, CC_LONG(d.count), &digest)
}
}
return (0..<length).reduce("") {
$0 + String(format: "%02x", digest[$1])
}
}
var token = "YourStrongKeyJpc3MiOiJodHRwczovL3NlY3VyZXRva2"
var algorithm: String = "AES/ECB/PKCS5padding"
var tokenRes = MD5(token)
let digest = hexstringToBytes(tokenRes!)
var skcSpec = SecretSpec()
skcSpec.secretSpec(key: digest!, algorithm: algorithm)
print("hello: \(skcSpec)")
let msg: NSMutableDictionary = NSMutableDictionary()
msg.setValue("data1", forKey: "phoneData")
msg.setValue("data2", forKey: "countryData")
let msgData: NSData
var msgStr: String = ""
var requestUrl: String = ""
do {
msgData = try JSONSerialization.data(withJSONObject: msg, options: JSONSerialization.WritingOptions()) as NSData
msgStr = NSString(data: msgData as Data, encoding: String.Encoding.utf8.rawValue)! as String
} catch _ {
print ("JSON Failure")
}
var str = skcSpec.getEncoded()
print(str)
let skc = NSString(bytes: str, length: str.count, encoding: String.Encoding.ascii.rawValue)! as String
let eneMsg = msgStr.aesEncrypt(key: skc)!
print("encoded: \(eneMsg)")
это не дает мне такой же вывод.Пожалуйста, помогите мне найти тот же результат.nb: java-код исправлен для шифрования и дешифрования.
* * 1 011 Выходы:
* * 1014 В Java: ffe957f00bdd93cfe1ef1133993cc9d2d8682310c648633660b448d92098e7fa07ae25f600467894ac94ccdcbe4039b8 * * 1016 в быстрой: 2e130be30aa3d8ff7fdc31dc8ffe1c39afe987ccbf8481caed9c78b49624a31c68df63a899df130128af6852c82d9aea