美文网首页
2018-06-25 使用CryptoSwift进行AES的EC

2018-06-25 使用CryptoSwift进行AES的EC

作者: LuSF | 来源:发表于2018-06-25 17:27 被阅读63次

    最近太忙了,没空写东西,刚下午搞了一下午CryptoSwift,搞出来了,所以把代码贴出来。

    需求是本地只保存用户的加密后的私钥,然后keystore就可以推出来,这样本地尽量少保存用户的钱包信息,密码也不会保存,因为密码是作为AES对称加密的时候的key使用的。不多BB了,还得继续改以前写好的代码,代码如下。

    在CryptoSwift没有大版本更新之前,你甚至可以直接复制过去用,前提是要决定采用:

    AES加密并且是ECB模式的加密方式

    //  CryptTools.swift
    //  Neuron
    //
    //  Created by XiaoLu on 2018/6/25.
    //  Copyright © 2018年 cryptape. All rights reserved.
    //
    
    import UIKit
    import CryptoSwift
    
    class CryptTools: NSObject {
        
        //encode
        public static func Endcode_AES_ECB(strToEncode:String,key:String)->String {
            
            var encodeString = ""
            do{
                
                let aes = try AES(key: Padding.zeroPadding.add(to: key.bytes, blockSize: AES.blockSize),blockMode: ECB())
                let encoded = try aes.encrypt(strToEncode.bytes)
                encodeString = encoded.toBase64()!
            }catch{
                print(error.localizedDescription)
            }
            return encodeString
        }
        
        //decode
        public static func Decode_AES_ECB(strToDecode:String,key:String)->String {
            
            var decodeStr = ""
            let data = NSData(base64Encoded: strToDecode, options: NSData.Base64DecodingOptions.init(rawValue: 0))
            var encrypted: [UInt8] = []
            let count = data?.length
            for i in 0..<count! {
                var temp:UInt8 = 0
                data?.getBytes(&temp, range: NSRange(location: i,length:1 ))
                encrypted.append(temp)
            }
            do {
                let aes = try AES(key: Padding.zeroPadding.add(to: key.bytes, blockSize: AES.blockSize),blockMode: ECB())
                let decode = try aes.decrypt(encrypted)
                let encoded = Data(decode)
                decodeStr = String(bytes: encoded.bytes, encoding: .utf8)!
            }catch{
                print(error.localizedDescription)
            }
            
            
            return decodeStr
        }
    }
    
    

    相关文章

      网友评论

          本文标题:2018-06-25 使用CryptoSwift进行AES的EC

          本文链接:https://www.haomeiwen.com/subject/ignyyftx.html