SHA-256算法【代码实现】

C

#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
 
int main (void) {
	const char *s = "Rosetta code";
	unsigned char *d = SHA256(s, strlen(s), 0);
 
	int i;
	for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
		printf("%02x", d[i]);
	putchar('\n');
 
	return 0;
}

C++

#include <iostream>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <cryptopp/sha.h>
 
int main(int argc, char **argv){
	CryptoPP::SHA256 hash;
	std::string digest;
	std::string message = "Rosetta code";
 
	CryptoPP::StringSource s(message, true,
			new CryptoPP::HashFilter(hash,
				new CryptoPP::HexEncoder(
					new CryptoPP::StringSink(digest))));
 
	std::cout << digest << std::endl;
 
	return 0;
}

C#

using System;
using System.Security.Cryptography;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
 
namespace RosettaCode.SHA256
{
    [TestClass]
    public class SHA256ManagedTest
    {
        [TestMethod]
        public void TestComputeHash()
        {
            var buffer = Encoding.UTF8.GetBytes("Rosetta code");
            var hashAlgorithm = new SHA256Managed();
            var hash = hashAlgorithm.ComputeHash(buffer);
            Assert.AreEqual(
                "76-4F-AF-5C-61-AC-31-5F-14-97-F9-DF-A5-42-71-39-65-B7-85-E5-CC-2F-70-7D-64-68-D7-D1-12-4C-DF-CF",
                BitConverter.ToString(hash));
        }
    }
}

Go

package main
 
import (
    "crypto/sha256"
    "fmt"
    "log"
)
 
func main() {
    h := sha256.New()
    if _, err := h.Write([]byte("Rosetta code")); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%x\n", h.Sum(nil))
}

输出:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Java

只需要把MD5算法里的"MD5"改成"SHA-256"

Kotlin

// version 1.0.6
 
import java.security.MessageDigest
 
fun main(args: Array<String>) {
    val text  = "Rosetta code"
    val bytes = text.toByteArray()
    val md = MessageDigest.getInstance("SHA-256")
    val digest = md.digest(bytes)
    for (byte in digest) print("%02x".format(byte))
    println() 
}

PHP

<?php
echo hash('sha256', 'Rosetta code');

Python

>>> import hashlib
>>> hashlib.sha256( "Rosetta code".encode() ).hexdigest()
'764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf'
>>> 
发布了56 篇原创文章 · 获赞 166 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_36721220/article/details/100730342
今日推荐