From f332b22248dd2ab0c08c2b257f90b1629c8f3023 Mon Sep 17 00:00:00 2001 From: Matthew Reishus Date: Thu, 4 Jan 2024 15:13:54 -0600 Subject: [PATCH] Experiment: Add SHA-256 response code --- src/components/results/response/index.jsx | 58 +++++++++++++++++++++-- 1 file changed, 54 insertions(+), 4 deletions(-) diff --git a/src/components/results/response/index.jsx b/src/components/results/response/index.jsx index a59ea0a..c1a85f6 100644 --- a/src/components/results/response/index.jsx +++ b/src/components/results/response/index.jsx @@ -6,19 +6,69 @@ import RequestBody from '../body'; import './style.css'; +async function sha256( message ) { + // encode as (utf-8) Uint8Array + const msgBuffer = new TextEncoder().encode( message ); + + // hash the message + const hashBuffer = await crypto.subtle.digest( 'SHA-256', msgBuffer ); + + // convert ArrayBuffer to Array + const hashArray = Array.from( new Uint8Array( hashBuffer ) ); + + // convert bytes to hex string + const hashHex = hashArray.map( ( b ) => ( '00' + b.toString( 16 ) ).slice( -2 ) ).join( '' ); + return hashHex; +} + class Index extends React.Component { state = { view: TREE_VIEW, + sha256Hash: '', + }; + componentDidMount() { + this.updateChecksum( this.props.result ); + } + + componentDidUpdate( prevProps ) { + const currentResponseJSON = JSON.stringify( this.props.result.response ); + const prevResponseJSON = JSON.stringify( prevProps.result.response ); + + if ( currentResponseJSON !== prevResponseJSON ) { + this.updateChecksum( this.props.result ); + } + } + + updateChecksum = async ( result ) => { + if ( result && result.response ) { + const hash = await sha256( JSON.stringify( result.response ) ); + this.setState( { sha256Hash: hash } ); + } }; - onViewChange = view => this.setState( { view } ); + onViewChange = ( view ) => this.setState( { view } ); render() { const { result } = this.props; + const { sha256Hash } = this.state; return ( -
- - +
+ + +
Response SHA-256: { sha256Hash }
); }