SHA-256

From Rosetta Code
Revision as of 23:49, 14 December 2012 by Grondilu (talk | contribs) (→‎{{header|Perl}}: style)
Task
SHA-256
You are encouraged to solve this task according to the task description, using any language you may know.

SHA-256 is the recommended stronger alternative to SHA-1.

Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

C

Requires OpenSSL, compile flag: -lssl <lang c>#include <stdio.h>

  1. include <string.h>
  2. 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; }</lang>

C#

<lang csharp>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));
       }
   }

}</lang>

Go

<lang 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))

}</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Java

The solution to this task would be a small modification to MD5 (replacing "MD5" with "SHA-256" as noted here).

Mathematica

<lang>IntegerString[Hash["Rosetta code", "SHA256"], 16]</lang>

Output:

764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

NetRexx

This solution is basically the same as that for MD5, substituting "SHA-256" for "MD5" as the algorithm to use in the MessageDigest instance. <lang NetRexx>/* NetRexx */ options replace format comments java crossref savelog symbols binary

import java.security.MessageDigest

SHA256('Rosetta code', '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf')

return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method SHA256(messageText, verifyCheck) public static

 algorithm   = 'SHA-256'
 digestSum = getDigest(messageText, algorithm)
 say '<Message>'messageText'</Message>'
 say Rexx('<'algorithm'>').right(12) || digestSum'</'algorithm'>'
 say Rexx('<Verify>').right(12) || verifyCheck'</Verify>'
 if digestSum == verifyCheck then say algorithm 'Confirmed'
                             else say algorithm 'Failed'
 return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method getDigest(messageText = Rexx, algorithm = Rexx 'MD5', encoding = Rexx 'UTF-8', lowercase = boolean 1) public static returns Rexx

 algorithm = algorithm.upper
 encoding  = encoding.upper
 message      = String(messageText)
 messageBytes = byte[]
 digestBytes  = byte[]
 digestSum    = Rexx 
 do
   messageBytes = message.getBytes(encoding)
   md = MessageDigest.getInstance(algorithm)
   md.update(messageBytes)
   digestBytes = md.digest
   loop b_ = 0 to digestBytes.length - 1
     bb = Rexx(digestBytes[b_]).d2x(2)
     if lowercase then digestSum = digestSum || bb.lower
                  else digestSum = digestSum || bb.upper
     end b_
 catch ex = Exception
   ex.printStackTrace
 end
 
 return digestSum

</lang> Output:

<Message>Rosetta code</Message>
   <SHA-256>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</SHA-256>
    <Verify>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</Verify>
SHA-256 Confirmed

Perl

<lang Perl>#!/usr/bin/perl use strict ; use warnings ; use Digest::SHA qw( sha256_hex ) ;

my $encoded = sha256_hex my $phrase = "Rosetta code" ; print "$phrase SHA256-encoded:\n$encoded\n" ; </lang> Output

Rosetta code SHA256-encoded:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Perl 6

<lang Perl 6>say .list».fmt("%02x").join given sha256 "Rosetta code".encode: "ascii";

sub init(&f, $n) {

   map { (($_ - .Int)*2**32).Int },
   map &f, (grep *.is-prime, 2 .. *)[^$n]

}

sub infix:<m+> { ($^a + $^b) % 2**32 } sub rotr($n, $b) { $n +> $b +| $n +< (32 - $b) }

sub sha256(Buf $data) returns Buf {

   my \K = init * **(1/3), 64;
   my $l = 8 * my @b = $data.list;
   push @b, 0x80; push @b, 0 until (8*@b-448) %% 512;
   push @b, reverse gather for ^8 { take $l%256; $l div=256 }
   my @word = gather for @b -> $a, $b, $c, $d {

take reduce * *256 + *, $a, $b, $c, $d;

   }
   my @H = init &sqrt, 8;
   my @w;
   loop (my $i = 0; $i < @word.elems; $i += 16) {

my @h = @H; for ^64 -> $j {

           @w[$j] = $j < 16 ?? @word[$j + $i] // 0 !!

[m+] rotr(@w[$j-15], 7) +^ rotr(@w[$j-15], 18) +^ @w[$j-15] +> 3, @w[$j-7], rotr(@w[$j-2], 17) +^ rotr(@w[$j-2], 19) +^ @w[$j-2] +> 10, @w[$j-16]; my $ch = @h[4] +& @h[5] +^ +^@h[4] % 2**32 +& @h[6]; my $maj = @h[0] +& @h[2] +^ @h[0] +& @h[1] +^ @h[1] +& @h[2]; my $σ0 = [+^] map { rotr @h[0], $_ }, 2, 13, 22; my $σ1 = [+^] map { rotr @h[4], $_ }, 6, 11, 25; my $t1 = [m+] @h[7], $σ1, $ch, K[$j], @w[$j]; my $t2 = $σ0 m+ $maj; @h = $t1 m+ $t2, @h[^3], @h[3] m+ $t1, @h[4..6]; } @H = @H Z[m+] @h;

   }
   return Buf.new: map -> $word is rw {

reverse gather for ^4 { take $word % 256; $word div= 256 }

   }, @H;

} </lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Python

Python has a standard module for this: <lang python>>>> import hashlib >>> hashlib.sha256( "Rosetta code" ).hexdigest() '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf' >>> </lang>

Ruby

<lang ruby>require 'digest/sha2' puts Digest::SHA256.hexdigest('Rosetta code')</lang>

Tcl

Library: Tcllib (Package: sha256)

<lang tcl>package require sha256

puts [sha2::sha256 -hex "Rosetta code"]</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf