OC 和 Swift4.2版 抑或(密钥)十六进制加解密

OC 版

//<Key: encryption and decryption key must be the same customizable

static NSString *secretKey =@"jwabcdefghijk";

#pragma mark - Encrypted string

+ (NSString *)encryptForPlainText:(NSString *)plainText {

    //Save the encrypted character

    NSMutableString *encryption = [NSMutableString string];

    //The string after the code conversion: UTF_8->iso-8859-1

    NSString *encoding = [[NSString alloc]initWithData:[plainText dataUsingEncoding:NSUTF8StringEncoding] encoding:NSISOLatin1StringEncoding];

    for(int i = 0,j = 0;i < encoding.length;i++,j++) {

        if(j == secretKey.length) {

            j = 0;

        }

        //Characters after XOR

        char cipher = (char)([encoding characterAtIndex:i]^[secretKey characterAtIndex:j]);

        //NSLog(@"%cTurn to a string of 16:%@,%@",cipher,[NSString stringWithFormat:@"%hhx",cipher],[NSString stringWithFormat:@"%x",cipher&0xff]);

        //Turn into a string in the form of 16, and x8b turns to a 8b string

        NSString *strCipher = [NSString stringWithFormat:@"%hhx",cipher];

        if(strCipher.length == 1) {

            [encryption appendFormat:@"0%@",strCipher];

        } else {

            [encryption appendString:strCipher];

        }

    }

    return encryption;

}

#pragma mark - Decryption, return the original character if not for the encrypted character

+ (NSString *)decryptForEncryption:(NSString *)encryptionText {

    //Save the decrypted character

    NSMutableString *decryption = [NSMutableString string];

    //Decoded character

    NSString *decoding = nil;

    for(int i = 0,j = 0;i < encryptionText.length / 2;i++,j++){

        if(j == secretKey.length){

            j = 0;

        }

        //Intercepting a string in a 16 - band form, 8b in x8b

        NSString *tem = [encryptionText substringWithRange:NSMakeRange(i * 2, 2)];

        char *endptr;

        //Turn a string of 16 in the form to a character

        char n = (char)(int)strtoul([tem UTF8String],&endptr,16);

        //Decide whether to be an encrypted character

        if (n == ''&& *endptr != '') {

            [decryption setString:@""];

            break;

        }

        [decryption appendFormat:@"%c",(char)(n^[secretKey characterAtIndex:j])];

    }

    if (![decryption isEqualToString:@""]) {

        //After the string encoding: iso-8859-1 - > UTF_8

        decoding = [[NSString alloc]initWithData:[[decryption copy] dataUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];

    }

    if (decoding == nil) {

        decoding = encryptionText;

    }

    return decoding;

}

Swift4.2版

新建 Data+Extension.swift

extension Data {

    /// Create hexadecimal string representation of `Data` object.

    /// - returns: `String` representation of this `Data` object.

    func hexadecimal() -> String {

        return map { String(format: "%02x", $0) }

            .joined(separator: "")

    }

}

新建 String+Extension.swift

extension String {

    /// Create `String` representation of `Data` created from hexadecimal string representation

    /// This takes a hexadecimal representation and creates a String object from that. Note, if the string has any spaces, those are removed. Also if the string started with a `<` or ended with a `>`, those are removed, too.

    /// For example,

    ///     String(hexadecimal: "<666f6f>")

    /// is

    ///     Optional("foo")

    /// - returns: `String` represented by this hexadecimal string.

    init?(hexadecimal string: String, encoding: String.Encoding = .utf8) {

        guard let data = string.hexadecimal() else {

            return nil

        }

        self.init(data: data, encoding: encoding)

    }

    

    /// Create `Data` from hexadecimal string representation

    /// This takes a hexadecimal representation and creates a `Data` object. Note, if the string has any spaces or non-hex characters (e.g. starts with '<' and with a '>'), those are ignored and only hex characters are processed.

    /// - returns: Data represented by this hexadecimal string.

    func hexadecimal() -> Data? {

        var data = Data(capacity: count / 2)

        let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive)

        regex.enumerateMatches(in: self, range: NSMakeRange(0, utf16.count)) { match, flags, stop in

            let byteString = (self as NSString).substring(with: match!.range)

            var num = UInt8(byteString, radix: 16)!

            data.append(&num, count: 1)

        }

        guard data.count > 0 else { return nil }

        return data

    }

    

    /// Create hexadecimal string representation of `String` object.

    /// For example,

    ///     "foo".hexadecimalString()

    /// is

    ///     Optional("666f6f")

    /// - parameter encoding: The `String.Encoding` that indicates how the string should be converted to `Data` before performing the hexadecimal conversion.

    /// - returns: `String` representation of this String object.

    func hexadecimalString(encoding: String.Encoding = .utf8) -> String? {

        return data(using: encoding)?

            .hexadecimal()

    }

}

DecoderUtil.swift

  

   private static let secretKey:NSString = "jwabcdefghijk"

    

    /* XOr encrypt

     * @param input NString to be encrypted

     * @return Encrypted NString

     */

    class func xorEncrypt(input: NSString) -> NSString? {

        let chars = (0..<input.length).map({

            input.character(at: $0)^secretKey.character(at: $0 % secretKey.length)

        })

        return  String(utf16CodeUnits: chars, count: chars.count).hexadecimalString()! as NSString

    }

    

    /* XOr Decrypt

     * @param input NString to decrypt

     * @return Decrypted NString

     */

    class func xorDecrypt(input: NSString) -> NSString? {

        let hexString = String(hexadecimal: input as String)! as NSString

        let chars = (0..<hexString.length).map({

            hexString.character(at: $0)^secretKey.character(at: $0 % secretKey.length)

        })

        return NSString(characters: chars, length: chars.count)

    }

Or

 /* XOr encrypt

     * @param input String to be encrypted

     * @return Encrypted string

     */

    class func xorEncrypt(input: String) -> String {

        let str = input as NSString

        let chars = (0..<str.length).map({

            str.character(at: $0)^secretKey.character(at: $0 % secretKey.length)

        })

        return  String(utf16CodeUnits: chars, count: chars.count).hexadecimalString()!

    }

    

    /* XOr Decrypt

     * @param input String to decrypt

     * @return Decrypted string

     */

    class func xorDecrypt(input: String) -> String {

        let hexString = String(hexadecimal: input)! as NSString

        let chars = (0..<hexString.length).map({

            hexString.character(at: $0)^secretKey.character(at: $0 % secretKey.length)

        })

        return String(utf16CodeUnits: chars, count: chars.count)

    }

原文地址:https://www.cnblogs.com/akiha/p/9907973.html