Java test

Java code posted
created at 24 Nov 13:32

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.io.*;
import java.net.*;
import java.security.*;
import java.util.*;

public class hmacSHA256 {
    public static String encrypt(
                        String message,
                        String keyStr) {

            //get the bytes of the keyStr
            byte[] key = keyStr.getBytes();
            // Start by getting an object to generate SHA-256 hashes with.
            MessageDigest sha256 = null;
            try {
                sha256 = MessageDigest.getInstance("SHA-256");
            } catch (NoSuchAlgorithmException e) {
                throw new java.lang.AssertionError(".hmacSHA256(): SHA-256 algorithm not found!");
            }
            // Hash the key if necessary to make it fit in a block (see RFC 2104).
            if (key.length > 64) {
               sha256.update(key);
                key = sha256.digest();
                sha256.reset();
            }

            // Pad the key bytes to a block (see RFC 2104).
            byte block[] = new byte[64];
            for (int i = 0; i < key.length; ++i) block[i] = key[i];
            for (int i = key.length; i < block.length; ++i) block[i] = 0;

            // Calculate the inner hash, defined in RFC 2104 as
            // SHA-256(KEY ^ IPAD + MESSAGE)), where IPAD is 64 bytes of 0x36.
            for (int i = 0; i < 64; ++i) block[i] ^= 0x36;
            sha256.update(block);
            try {
                sha256.update(message.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new java.lang.AssertionError(
                        "ITunesU.hmacSH256(): UTF-8 encoding not supported!");
            }
            byte[] hash = sha256.digest();
            sha256.reset();

            // Calculate the outer hash, defined in RFC 2104 as
            // SHA-256(KEY ^ OPAD + INNER_HASH), where OPAD is 64 bytes of 0x5c.
            for (int i = 0; i < 64; ++i) block[i] ^= (0x36 ^ 0x5c);
            sha256.update(block);
            sha256.update(hash);
            hash = sha256.digest();

            // The outer hash is the message signature...
            // convert its bytes to hexadecimals.
            char[] hexadecimals = new char[hash.length * 2];
            for (int i = 0; i < hash.length; ++i) {
                for (int j = 0; j < 2; ++j) {
                    int value = (hash[i] >> (4 - 4 * j)) & 0xf;
                    char base = (value < 10) ? ('0') : ('a' - 10);
                    hexadecimals[i * 2 + j] = (char)(base + value);
                }
            }

            // Return a hexadecimal string representation of the message signature.
            return new String(hexadecimals);
    }
} 
2.69 KB in 5 ms with coderay