07-16-2012 08:40 AM
I am looking to SHA encrypt a string value in BB, but some of the BB classes shows some samples which returns the length of hMAC
ie,
private static int sampleSHA256HMAC( byte[] hashKey, byte[] plainText, byte[] digestData )
throws CryptoException, IOException
{
// Create the keyed hash function key
HMACKey key = new HMACKey( hashKey );
// Create an instance of an HMAC
HMAC hMac = new HMAC( key, new SHA256Digest() );
// Now create the MAC output stream for easy use
MACOutputStream macStream = new MACOutputStream( hMac, null );
// Write the text to the stream
macStream.write( plainText );
// Copy the digest data to the digestData byte array and
// return the length
hMac.getMAC( digestData, 0 );
return hMac.getLength();
}
Is there any way to SHA encrypt a string to return a string value(hash value) of the string as string itself.
Solved! Go to Solution.
07-16-2012 09:27 AM
You should be aware that SHA does not encrypt, it is a hash algorithm which calculates the hash of some bytes. it is not possible to recover the bytes from the hash.
I suggest you review the actual specification of this algorithm. If you are looking for something to encrypt and/or create a String, then you need to look at some other algorithm.
if you want to stick with SHA-2, then just convert the int to a String.
07-17-2012 09:10 AM
Hi.
If you consider what peter_strange said about not being an encription algorithm and you still want to use it, try this method. It returns a String
private String sign(String content) throws Exception {
HMAC sha256 = new HMAC(new HMACKey(secretAccessKey.getBytes()),
new SHA256Digest());
sha256.update(content.getBytes());
byte[] signed = new byte[sha256.getLength()];
sha256.getMAC(signed, 0);
String signedbase64 = Base64OutputStream.encodeAsString(signed, 0, signed.length, false, false);
return signedbase64;
}
Well, it actually returns a URLUTF8 encode version of the Base64 String but you get the idea.
The secretAccessKey object is a String needed to hash your content. I suppose you'll place your own key there.
In summary:
- Create the HMAC object using your key.
- Fill it with your content.
- Create a byte[] to place the hash.
- Fill the array with the hashed content.
- Convert the bytes to String (I used base 64 but I guess you could simply use new String(byte[]))
I hope it helps.
Cheers.