=========== swift Base64编码解码==========
/**
* 编码
*/
func base64Encoding(str:String)->String
{
let strData = str.data(using: String.Encoding.utf8)
let base64String = strData?.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))
return base64String!
}
/**
* 解码
*/
func base64Decoding(encodedStr:String)->String
{
let decodedData = NSData(base64Encoded: encodedStr, options: NSData.Base64DecodingOptions.init(rawValue: 0))
let decodedString = NSString(data: decodedData! as Data, encoding: String.Encoding.utf8.rawValue)! as String
return decodedString
}
===========MD5=======
//桥接文件中导入
#import
MD5算法
extension String{
func md5() ->String!{
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
var hash = NSMutableString()
for i in 0 ..< digestLen {
hash.appendFormat("%02x", result[i])
}
result.destroy()
return String(format: hash as String)
}
}
调用MD5算法
var str = "test"
var str_MD5 = str.md5()
==========sha1=======
建立桥接文件中 #import
创建string的扩展
extension String {
//MARK: - MD5
func md5() -> String {
let cStr = self.cString(using: String.Encoding.utf8);
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)
CC_MD5(cStr!,(CC_LONG)(strlen(cStr!)), buffer)
let md5String = NSMutableString();
for i in 0 ..< 16{
md5String.appendFormat("%02x", buffer[i])
}
free(buffer)
return md5String as String
}
//MARK: - sha1 加密
func sha1() -> String {
let data = self.data(using: String.Encoding.utf8)!
var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
let newData = NSData.init(data: data)
CC_SHA1(newData.bytes, CC_LONG(data.count), &digest)
let output = NSMutableString(capacity: Int(CC_SHA1_DIGEST_LENGTH))
for byte in digest {
output.appendFormat("%02x", byte)
}
return output as String
}
}
使用时候,代码如下:
let string = "123456"
let string_md5 = string.md5()
let string_sha1 = string.sha1()