不同程序语言处理加密算法的性能对比,PHP/Golang/NodeJS

首先上我最常用且最易用的PHP来做下测试

<?php

function test_encrypt($fun, $max) {
    $begin = microtime(TRUE);
    $pwdpre = time();
    for ($i = 1; $i <= $max; $i++) {
        $fun($pwdpre . $i);
    }
    echo $fun . ' => ' . number_format((microtime(TRUE) - $begin) * 1000, 2) . ' ms' . "\r\n";
}

test_encrypt('crc32', 1000 * 1000); //165.52ms
test_encrypt('md5', 1000 * 1000); //390.99ms
test_encrypt('sha1', 1000 * 1000); //488.63.ms

下面贴上很多人觉得性能不错的Golang来做下测试

package main

import (
    "crypto/md5"
    "crypto/sha1"
    "encoding/hex"
    "fmt"
    "hash/crc32"
    "strconv"
    "time"
)

func main() {
    test_encrypt("CRC32", 1000*1000) // 162.1024 ms
    test_encrypt("MD5", 1000*1000)   // 525.0696 ms
    test_encrypt("SHA1", 1000*1000)  // 586.758 ms
}

func test_encrypt(fun string, max int) {
    pwdpre := strconv.FormatInt(time.Now().Unix(), 10)
    begin := time.Now().UnixNano()
    for i := 1; i <= max; i++ {
        switch fun {
        case "CRC32":
            CRC32(pwdpre + strconv.Itoa(i))
        case "MD5":
            MD5(pwdpre + strconv.Itoa(i))
        case "SHA1":
            SHA1(pwdpre + strconv.Itoa(i))
        }

    }
    end := time.Now().UnixNano()
    fmt.Println(fun, "=>", float64(end-begin)/1e6, "ms")
}
func MD5(str string) string {
    // 取得16进制文本MD5
    h := md5.New()
    h.Write([]byte(str))
    return hex.EncodeToString(h.Sum(nil))
}

func SHA1(str string) string {
    // 取得16进制文本SHA1
    c := sha1.New()
    c.Write([]byte(str))
    return hex.EncodeToString(c.Sum(nil))
}

func CRC32(str string) uint32 {
    // 取得无符号32位整型CRC32
    return crc32.ChecksumIEEE([]byte(str))
}