44import com .facebook .react .bridge .ReactApplicationContext ;
55import com .facebook .react .bridge .ReactContextBaseJavaModule ;
66import com .facebook .react .bridge .ReactMethod ;
7+ import com .facebook .react .bridge .ReadableArray ;
78import com .facebook .react .bridge .Callback ;
89import com .facebook .react .bridge .Promise ;
910
@@ -28,13 +29,29 @@ public String getName() {
2829 return "sha256Lib" ;
2930 }
3031
32+ private static byte [] readableArrayToByteArray (ReadableArray readableArray ) {
33+ byte [] arr = new byte [readableArray .size ()];
34+ for (int i = 0 ; i < readableArray .size (); ++i ) {
35+ arr [i ] = (byte ) readableArray .getInt (i );
36+ }
37+
38+ return arr ;
39+ }
40+
3141 String buildHash (final String toHash , final String algo , final Integer length ) throws NoSuchAlgorithmException , UnsupportedEncodingException {
3242 MessageDigest md = MessageDigest .getInstance (algo );
3343 md .update (toHash .getBytes ("UTF-8" ));
3444 byte [] digest = md .digest ();
3545 return String .format ("%0" + length .toString () + "x" , new java .math .BigInteger (1 , digest ));
3646 }
3747
48+ String buildHashWithBytes (final ReadableArray toHash , final String algo , final Integer length ) throws NoSuchAlgorithmException , UnsupportedEncodingException {
49+ MessageDigest md = MessageDigest .getInstance (algo );
50+ byte [] arr = Sha256Module .readableArrayToByteArray (toHash );
51+ md .update (arr );
52+ byte [] digest = md .digest ();
53+ return String .format ("%0" + length .toString () + "x" , new java .math .BigInteger (1 , digest ));
54+ }
3855
3956 @ ReactMethod
4057 public void sha256 (final String toHash , Promise promise ) {
@@ -50,6 +67,20 @@ public void sha256(final String toHash, Promise promise) {
5067 }
5168 }
5269
70+ @ ReactMethod
71+ public void sha256Bytes (final ReadableArray toHash , Promise promise ) {
72+ try {
73+ String hash = buildHashWithBytes (toHash , "SHA-256" , 64 );
74+ promise .resolve (hash );
75+ } catch (NoSuchAlgorithmException e ) {
76+ e .printStackTrace ();
77+ promise .reject ("sha256" , e .getMessage ());
78+ } catch (UnsupportedEncodingException e ) {
79+ e .printStackTrace ();
80+ promise .reject ("sha256" , e .getMessage ());
81+ }
82+ }
83+
5384 @ ReactMethod
5485 public void sha1 (final String toHash , Promise promise ) {
5586 try {
@@ -64,4 +95,18 @@ public void sha1(final String toHash, Promise promise) {
6495 }
6596 }
6697
98+ @ ReactMethod
99+ public void sha1Bytes (final ReadableArray toHash , Promise promise ) {
100+ try {
101+ String hash = buildHashWithBytes (toHash , "SHA-1" , 40 );
102+ promise .resolve (hash );
103+ } catch (NoSuchAlgorithmException e ) {
104+ e .printStackTrace ();
105+ promise .reject ("sha1" , e .getMessage ());
106+ } catch (UnsupportedEncodingException e ) {
107+ e .printStackTrace ();
108+ promise .reject ("sha1" , e .getMessage ());
109+ }
110+ }
111+
67112}
0 commit comments