In Swift, it is convenient to convert string strings to SHA1 by calling OC's Commoncrypto library.
In a swift project, you need to use the bridge header file (bridging header) to introduce an OC library in order to invoke the content in OC.
This article will also be an introduction to how to invoke the Objective-c code in the Swift project.
Standard implementation Steps
1. Create a new objective-c m file
2, click Next, enter the filename (this file can be deleted), select the save location, the default directly OK, save in the current project directory, then Xcode will automatically prompt us whether to create a bridging file:
3, yes, Xode automatically created a swift and OC bridging file for us: project name-bridging-header.h
Here, we can remove the TEST.M file and call SHA1 to implement nothing in M.
4. In the Bridging-header.h file, enter:
// Use sha1 algorithm in Swift to introduce this library
#import <CommonCrypto / CommonCrypto.h>
Just like this:
5. Write a string extension (extension) in your project (for example, in a swift file) with the following code:
extension String {
func sha1() -> String {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
let hexBytes = map(digest) { String(format: "%02hhx", $0) }
return "".join(hexBytes)
}
}
6. Start using, code:
var password = txtPasswd.text
password = password.sha1()
Obtain the user-entered password from an input box, and then call the SHA1 method directly to get the SHA1 value of the password.
It's very convenient.
Virgo Manual Implementation steps
1, in the standard step, we are through the new M file, then Xcode automatically prompts for us to create a bridge header file, here we can ignore this step, directly create an h file, manually the H file as a bridge header file.
2. Select the Project root node, select "Build Settings" in the configuration on the right, then locate the "Swift Compiler" node below, select the "Objective-c Bridging Header" entry and double-click the path of the H file you just created:
3, now, as in the standard steps, the introduction of the Commoncrypto Library in the Header.h file, create a string class extension, you can begin to use!
Resources
Http://stackoverflow.com/questions/25761344/how-to-crypt-string-to-sha1-with-swift
Tips
This article consists of Wp2osc Import, original link: http://devonios.com/swift-sha1.html
because the Oschina OPENAPI automatically filters the IMG tag when processing the content parameter, the picture cannot be displayed, See .
Swift calls the SHA1 algorithm