Concept Explanation: Message Digest (abstract) algorithm (algorithm): Information Digest algorithm Fifth edition
is to program any length of byte string to a certain length of hexadecimal string
Characteristics
1, compressibility: Any length of data, calculated the length of the MD5 value is fixed.
2, easy to calculate: It is easy to calculate the MD5 value from the original data.
3, anti-modification: Any changes to the original data, even if only 1 bytes modified, the resulting MD5 value is very different.
4, strong anti-collision: known raw data and its MD5 value, it is very difficult to find a data with the same MD5 value (that is, falsification of data).
The output of the algorithm consists of four 32-bit groupings, which will generate a 128-bit hash value after cascading the four 32-bit groupings, eventually returning a 128-bit 1 or 0
This algorithm is irreversible.
This algorithm can help you see if the file has been modified.
- Swift
struct Md5utility {static func getmd5fromstring (string:string), nsmutablestring {Let original = String.c Stringusingencoding (nsutf8stringencoding) Let digest = Unsafemutablepointer<uint8>.alloc (+) Let Lengt h = UInt32 (strlen (original!)) CC_MD5 (original!, Length, Digest) return Getmd5str (Digest)} static func Getmd5fromdata (Data:nsdata)-&G T nsmutablestring {Let original = data.bytes let Ori = Unsafebitcast (Original, unsafepointer<int8>.self Let Md5length = Int (cc_md5_digest_length) Let DIGEST = Unsafemutablepointer<uint8>.alloc (MD5 Length) Let length = UInt32 (strlen (ori)) Cc_md5 (original, length, digest) return Getmd5str (di Gest)} static func Getmd5fromfilepath (path:string), nsmutablestring {let Handel = Nsfileh Andle (forreadingatpath:path) if Handel = = nil {print ("failed") returN nsmutablestring (string: "File is not opened")}//Declaration of a contextual context var context = Cc_md5_ctx () Initializes a context cc_md5_init (&context) var do = true while doing {var data = ha Ndel?. Readdataoflength (1024)//Update the context cc_md5_update (&context, &data, UInt32 (data?. Length).)) If data?. Length = = 0 {done = false}} Let Digest = unsafemutablepointer<uint8& gt;. Alloc (16)//Finalize Context Cc_md5_final (Digest, &context) return Getmd5str (Digest)} private static Func Getmd5str (digest:unsafemutablepointer<uint8>), nsmutablestring {Let md5string = NS Mutablestring (CAPACITY:16 * 2) for index in 0..<16 {md5string.appendformat ("%02x", digest[i Ndex])} Digest.destroy () return md5string}}
MD5 encrypting files, strings, data