HarmonyOS 鸿蒙Next中MD5加密算法demo

HarmonyOS 鸿蒙Next中MD5加密算法demo 求一个MD5加密算法demo

4 回复

在Harmony中可以采用以下两种写法进行相关数据的md5加密:

//写法一
toMD5A(content: string) { //content为传入的待转换成md的参数
    let md = cryptoFramework.createMd('MD5');
    md.update({ data: new Uint8Array(buffer.from(content, 'utf-8').buffer } , (error) => {
        md.digest((error, digestOutput) => {
            console.log(this.message, `MD5 result is : ${digestOutput.data}`);
            //转换为16进制字符串并输出
            const result = Array.from(digestOutput.data).map(byte => byte.toString(16)).join('')
            console.info("xxxx:",result)
        })
    })
}

//写法二
async toMD5B(content: string) {
    let md = cryptoFramework.createMd('MD5');
    await md.update({ data: new Uint8Array(buffer.from(content, 'utf-8').buffer });
    let mdOutput = await md.digest();
    console.info('[Promise]: MD result1: ' + mdOutput.data);
    const result = Array.from(mdOutput.data).map(byte => byte.toString(16)).join('')
    console.info("ssss:",result)
}

更多关于HarmonyOS 鸿蒙Next中MD5加密算法demo的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


export default class MD5Util{
  private static instance:MD5Util;

  private salt: string = 'FQBLZPQ3PWJ48AV63DWEWTRE345'

  private constructor() {
  }

  public static getInstance():MD5Util{
    if (!MD5Util.instance) {
      MD5Util.instance = new MD5Util();
    }
    return MD5Util.instance
  }

  public md5AndSalt(input: string): string {
    return this.md5(this.md5(input)+this.salt)
  }
  // 主加密方法
  public md5(input: string): string {
    // 将字符串转换为 UTF-8 字节数组
    const bytes = this.strToUTF8Bytes(input);
    // 对字节数组进行填充
    const paddedBytes = this.padBytes(bytes);
    // 分块处理数据
    const blocks = this.bytesToBlocks(paddedBytes);


    let a = 0x67452301;
    let b = 0xefcdab89;
    let c = 0x98badcfe;
    let d = 0x10325476;
    // 初始化状态变量
    //let [a, b, c, d] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];

    // 处理每个 512 位块
    for (const block of blocks) {
      // 保存原始状态
      // const [aa, bb, cc, dd] = [a, b, c, d];
      const aa = a;
      const bb = b;
      const cc = c;
      const dd = d;

      // 四轮主循环处理
      a = this.ff(a, b, c, d, block[0], 7, 0xd76aa478);
      d = this.ff(d, a, b, c, block[1], 12, 0xe8c7b756);
      c = this.ff(c, d, a, b, block[2], 17, 0x242070db);
      b = this.ff(b, c, d, a, block[3], 22, 0xc1bdceee);
      a = this.ff(a, b, c, d, block[4], 7, 0xf57c0faf);
      d = this.ff(d, a, b, c, block[5], 12, 0x4787c62a);
      c = this.ff(c, d, a, b, block[6], 17, 0xa8304613);
      b = this.ff(b, c, d, a, block[7], 22, 0xfd469501);
      a = this.ff(a, b, c, d, block[8], 7, 0x698098d8);
      d = this.ff(d, a, b, c, block[9], 12, 0x8b44f7af);
      c = this.ff(c, d, a, b, block[10], 17, 0xffff5bb1);
      b = this.ff(b, c, d, a, block[11], 22, 0x895cd7be);
      a = this.ff(a, b, c, d, block[12], 7, 0x6b901122);
      d = this.ff(d, a, b, c, block[13], 12, 0xfd987193);
      c = this.ff(c, d, a, b, block[14], 17, 0xa679438e);
      b = this.ff(b, c, d, a, block[15], 22, 0x49b40821);

      a = this.gg(a, b, c, d, block[1], 5, 0xf61e2562);
      d = this.gg(d, a, b, c, block[6], 9, 0xc040b340);
      c = this.gg(c, d, a, b, block[11], 14, 0x265e5a51);
      b = this.gg(b, c, d, a, block[0], 20, 0xe9b6c7aa);
      a = this.gg(a, b, c, d, block[5], 5, 0xd62f105d);
      d = this.gg(d, a, b, c, block[10], 9, 0x02441453);
      c = this.gg(c, d, a, b, block[15], 14, 0xd8a1e681);
      b = this.gg(b, c, d, a, block[4], 20, 0xe7d3fbc8);
      a = this.gg(a, b, c, d, block[9], 5, 0x21e1cde6);
      d = this.gg(d, a, b, c, block[14], 9, 0xc33707d6);
      c = this.gg(c, d, a, b, block[3], 14, 0xf4d50d87);
      b = this.gg(b, c, d, a, block[8], 20, 0x455a14ed);
      a = this.gg(a, b, c, d, block[13], 5, 0xa9e3e905);
      d = this.gg(d, a, b, c, block[2], 9, 0xfcefa3f8);
      c = this.gg(c, d, a, b, block[7], 14, 0x676f02d9);
      b = this.gg(b, c, d, a, block[12], 20, 0x8d2a4c8a);

      a = this.hh(a, b, c, d, block[5], 4, 0xfffa3942);
      d = this.hh(d, a, b, c, block[8], 11, 0x8771f681);
      c = this.hh(c, d, a, b, block[11], 16, 0x6d9d6122);
      b = this.hh(b, c, d, a, block[14], 23, 0xfde5380c);
      a = this.hh(a, b, c, d, block[1], 4, 0xa4beea44);
      d = this.hh(d, a, b, c, block[4], 11, 0x4bdecfa9);
      c = this.hh(c, d, a, b, block[7], 16, 0xf6bb4b60);
      b = this.hh(b, c, d, a, block[10], 23, 0xbebfbc70);
      a = this.hh(a, b, c, d, block[13], 4, 0x289b7ec6);
      d = this.hh(d, a, b, c, block[0], 11, 0xeaa127fa);
      c = this.hh(c, d, a, b, block[3], 16, 0xd4ef3085);
      b = this.hh(b, c, d, a, block[6], 23, 0x04881d05);
      a = this.hh(a, b, c, d, block[9], 4, 0xd9d4d039);
      d = this.hh(d, a, b, c, block[12], 11, 0xe6db99e5);
      c = this.hh(c, d, a, b, block[15], 16, 0x1fa27cf8);
      b = this.hh(b, c, d, a, block[2], 23, 0xc4ac5665);

      a = this.ii(a, b, c, d, block[0], 6, 0xf4292244);
      d = this.ii(d, a, b, c, block[7], 10, 0x432aff97);
      c = this.ii(c, d, a, b, block[14], 15, 0xab9423a7);
      b = this.ii(b, c, d, a, block[5], 21, 0xfc93a039);
      a = this.ii(a, b, c, d, block[12], 6, 0x655b59c3);
      d = this.ii(d, a, b, c, block[3], 10, 0x8f0ccc92);
      c = this.ii(c, d, a, b, block[10], 15, 0xffeff47d);
      b = this.ii(b, c, d, a, block[1], 21, 0x85845dd1);
      a = this.ii(a, b, c, d, block[8], 6, 0x6fa87e4f);
      d = this.ii(d, a, b, c, block[15], 10, 0xfe2ce6e0);
      c = this.ii(c, d, a, b, block[6], 15, 0xa3014314);
      b = this.ii(b, c, d, a, block[13], 21, 0x4e0811a1);
      a = this.ii(a, b, c, d, block[4], 6, 0xf7537e82);
      d = this.ii(d, a, b, c, block[11], 10, 0xbd3af235);
      c = this.ii(c, d, a, b, block[2], 15, 0x2ad7d2bb);
      b = this.ii(b, c, d, a, block[9], 21, 0xeb86d391);

      // 更新状态变量
      a = (a + aa) >>> 0;
      b = (b + bb) >>> 0;
      c = (c + cc) >>> 0;
      d = (d + dd) >>> 0;
    }

    // 将结果转换为小端字节序并生成十六进制字符串
    return (this.toHexLittleEndian(a) +
    this.toHexLittleEndian(b) +
    this.toHexLittleEndian(c) +
    this.toHexLittleEndian(d)).toUpperCase();
  }

  // 辅助方法:将字符串转换为UTF-8字节数组
  private  strToUTF8Bytes(str: string): Uint8Array {
    const bytes: number[] = [];
    for (let i = 0; i < str.length; i++) {
      let code = str.charCodeAt(i);
      if (code < 0x80) {
        bytes.push(code);
      } else if (code < 0x800) {
        bytes.push(0xc0 | (code >> 6));
        bytes.push(0x80 | (code & 0x3f));
      } else if (code < 0x10000) {
        bytes.push(0xe0 | (code >> 12));
        bytes.push(0x80 | ((code >> 6) & 0x3f));
        bytes.push(0x80 | (code & 0x3f));
      } else {
        bytes.push(0xf0 | (code >> 18));
        bytes.push(0x80 | ((code >> 12) & 0x3f));
        bytes.push(0x80 | ((code >> 6) & 0x3f));
        bytes.push(0x80 | (code & 0x3f));
      }
    }
    return new Uint8Array(bytes);
  }

  // 辅助方法:字节数组填充
  private  padBytes(bytes: Uint8Array): Uint8Array {
    const bitLength = bytes.length * 8;
    const newBytes = new Uint8Array(((bytes.length + 8) >>> 6) + 1 * 64);
    newBytes.set(bytes);

    // 添加填充位
    newBytes[bytes.length] = 0x80;

    // 添加长度信息(小端序)
    const lenBytes = new Uint8Array(8);
    const lenView = new DataView(lenBytes.buffer);
    lenView.setUint32(0, bitLength, true);
    lenView.setUint32(4, 0, true);
    newBytes.set(lenBytes, newBytes.length - 8);

    return newBytes;
  }

  // 辅助方法:将字节数组转换为32位字数组块
  private  bytesToBlocks(bytes: Uint8Array): Uint32Array[] {
    const blocks: Uint32Array[] = [];
    for (let i = 0; i < bytes.length; i += 64) {
      const block = new Uint32Array(16);
      const view = new DataView(bytes.buffer, i, 64);
      for (let j = 0; j < 16; j++) {
        block[j] = view.getUint32(j * 4, true);
      }
      blocks.push(block);
    }
    return blocks;
  }

  // 四轮操作函数
  private ff(a: number, b: number, c: number, d: number, m: number, s: number, t: number): number {
    return this.cmn((b & c) | (~b & d), a, b, m, s, t);
  }

  private gg(a: number, b: number, c: number, d: number, m: number, s: number, t: number): number {
    return this.cmn((b & d) | (c & ~d), a, b, m, s, t);
  }

  private hh(a: number, b: number, c: number, d: number, m: number, s: number, t: number): number {
    return this.cmn(b ^ c ^ d, a, b, m, s, t);
  }

  private ii(a: number, b: number, c: number, d: number, m: number, s: number, t: number): number {
    return this.cmn(c ^ (b | ~d), a, b, m, s, t);
  }

  // 通用循环操作
  private cmn(q: number, a: number, b: number, m: number, s: number, t: number): number {
    const res = (a + q + m + t) >>> 0;
    return ((res << s) | (res >>> (32 - s))) + b >>> 0;
  }

  // 将32位数转换为小端序十六进制
  private toHexLittleEndian(num: number): string {
    const bytes = new Uint8Array(4);
    const view = new DataView(bytes.buffer);
    view.setUint32(0, num, true);
    return Array.from(bytes)
      .map(b => b.toString(16).padStart(2, '0'))
      .join('');
  }
}

在HarmonyOS(鸿蒙)Next中,MD5加密算法可以通过使用ohos.security.crypto模块来实现。以下是一个简单的MD5加密算法示例:

import crypto from '@ohos.security.crypto';

function md5Encrypt(input: string): string {
    const md5 = crypto.createHash('md5');
    md5.update(input);
    return md5.digest('hex');
}

// 示例使用
const input = 'Hello, HarmonyOS!';
const encrypted = md5Encrypt(input);
console.log('MD5加密结果:', encrypted);

在这个示例中,我们使用@ohos.security.crypto模块中的createHash方法创建了一个MD5哈希对象,并通过update方法将输入字符串添加到哈希对象中。最后,使用digest方法生成MD5加密结果的十六进制字符串表示。

在HarmonyOS(鸿蒙)Next中,你可以使用Java标准库中的MessageDigest类来实现MD5加密。以下是一个简单的MD5加密示例代码:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Example {
    public static String md5(String input) {
        try {
            // 创建MD5实例
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 将输入字符串转换为字节数组并计算摘要
            byte[] digest = md.digest(input.getBytes());
            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                hexString.append(String.format("%02x", b));
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String input = "Hello, HarmonyOS!";
        String encrypted = md5(input);
        System.out.println("MD5加密结果: " + encrypted);
    }
}

这个示例展示了如何将字符串进行MD5加密,并将结果转换为十六进制字符串输出。

回到顶部