如何在swift中将字符串

如何在swift中将字符串

本文介绍了如何在swift中将字符串(在Java中使用加密MessageDigest)编码为Base64字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我使用了这个:

In Java, I used this:

public void encryptData() {
    String data = "Hello World";
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    if (md == null) {
        return;
    }
    md.update(data.getBytes());
    String dataEncoded = Base64.encodeToString(md.digest(), 11);
    return dataEncoded; //print: sQqNsWTgdUEFt6mb5y4_5Q
}

如何在Swift中获得相同的结果?

How do I do have the same results in Swift?

更新:

func test() -> Void {
    var data: String = "Hello World"
    data = md5(data)
    data = base64Encode(data)
    print("data = \(data)") //YjEwYThkYjE2NGUwNzU0MTA1YjdhOTliZTcyZTNmZTU=
}

MD5和从和

任何提示都会有所帮助。

Any hints will be helpful.

推荐答案

您的代码不会产生预期的结果,因为
引用的 md5()函数返回消息摘要作为
十六进制编码的字符串,然后进行Base64编码。因此,而不是

Your code does not produce the expected result because thereferenced md5() function returns the message digest as ahex-encoded string, which is then Base64 encoded. So instead of

 String -> UTF-8 data -> MD5 digest -> Base64 encoding

你正在做什么

 String -> UTF-8 data -> MD5 digest -> hex encoding -> Base64 encoding

该函数的一个小修改将消息摘要
作为数据返回:

A small modification of the function returns the message digestas data:

func md5(string string: String) -> NSData {
    var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
    let data = string.dataUsingEncoding(NSUTF8StringEncoding)! // Conversion to UTF-8 cannot fail
    CC_MD5(data.bytes, CC_LONG(data.length), &digest)
    return NSData(bytes: digest, length: digest.count)
}

现在你可以计算Base 64编码的MD5摘要:

Now you can compute the Base 64 encoded MD5 digest:

let string = "Hello World"

// Compute MD5 message digest:
let md5data = md5(string: string)
print("md5data = \(md5data)") // md5data = <b10a8db1 64e07541 05b7a99b e72e3fe5>

// Convert to Base 64 encoded string:
let base64 = md5data.base64EncodedStringWithOptions([])
print("base64 = \(base64)") // base64 = sQqNsWTgdUEFt6mb5y4/5Q==

几乎您的期望。 Java代码显然产生
所谓的base64url变体而没有填充
(比较)。

This is almost what you expect. The Java code apparently producesthe so-called "base64url" variant without padding(compare https://en.wikipedia.org/wiki/Base64#Variants_summary_table).

因此我们必须修改两个字符并删除填充:

Therefore we have to modify two characters and remove the padding:

let base64url = base64
    .stringByReplacingOccurrencesOfString("+", withString: "-")
    .stringByReplacingOccurrencesOfString("/", withString: "_")
    .stringByReplacingOccurrencesOfString("=", withString: "")
print("base64url = \(base64url)") // base64url = sQqNsWTgdUEFt6mb5y4_5Q

现在结果是 sQqNsWTgdUEFt6mb5y4_5Q ,并且相同于你从Java代码得到了什么

Now the result is sQqNsWTgdUEFt6mb5y4_5Q, and identical to whatyou got from the Java code.

这篇关于如何在swift中将字符串(在Java中使用加密MessageDigest)编码为Base64字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:12