SHA-256アルゴリズム【コード実装】


C
#include 
#include 
#include 
 
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('
'
); return 0; }

C++
#include 
#include 
#include 
#include 
 
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
"
, h.Sum(nil)) }

出力:764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcfJava
MD 5アルゴリズムの「MD 5」を「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

echo hash('sha256', 'Rosetta code');

Python
>>> import hashlib
>>> hashlib.sha256( "Rosetta code".encode() ).hexdigest()
'764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf'
>>>