特定の文字列をSHA256でハッシュ化

Contents

出力結果

9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08

プログラムコード

JavaScript

const crypto = require('crypto');
class HashStrCreator {
	constructor(opt) {
    }

	convert(str) {
        return crypto.createHash('sha256').update(str, 'utf8').digest('hex');
    }
};
module.exports = HashStrCreator;

if(!module.parent) {
    const example_str = 'test';
	let hc = new HashStrCreator({});
	console.log(hc.convert(example_str));
}

Perl

package HashStrCreator;
use Digest::SHA qw(sha256_hex);
use strict;
use warnings;
 
sub new(){
    my $self = {};
    return bless($self);
}

sub convert(){
    my $self = shift;
    my $str = shift;
    return sha256_hex($str);
}

if ($0 eq __FILE__) {
    my $example_str = 'test';
    my $hc = new HashStrCreator();
    print($hc->convert($example_str)."\n");
}
else{
    return 0;
}

PHP

<?php
class HashStrCreator {
    public function __constructor() {
    }

    public function convert($str){
        return hash('sha256', $str);
    }
}

if ( !isset(debug_backtrace()[0]) ) {
    $example_str = 'test';
    $hc = new HashStrCreator();
    print($hc->convert($example_str)."\n");
}

Python

import hashlib

class HashStrCreator:
    def __init__(self):
        pass

    def convert(self, str):
        return hashlib.sha256(str.encode("utf-8")).hexdigest()

if __name__ == "__main__":
    example_str = 'test'
    hc = HashStrCreator()
    print(hc.convert(example_str))

Ruby

require 'digest'

class HashStrCreator
    def initialize(opt)
    end

    def convert(str)
        return str
    end
end

if $0 == __FILE__
    example_str = 'test'
    hc = HashStrCreator.new({})
    puts hc.convert(Digest::SHA256.hexdigest example_str)
end

Shell

#!/bin/bash
EexampleStr=test;
echo -n $EexampleStr|openssl dgst -sha256;