Java tutorial
package com.gmu.uav; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Hex; /* * ECE798 - UAV RESEARCH PROJECT * GEORGE MASON UNIVERSITY * ANDREW KEENE * SUMMER/FALL 2012 * * Code Source Repository: http://code.google.com/p/gmu-ece798-research-project-uav/ * Code License: GNU GPL V3 * * RadioSecurity.class : This class consists of the functions required to authenticate with the ground system. * Functions for computing the SHA256 and HMAC-SHA1 of a given ASCII String are found here. * */ public class RadioSecurity { public static final int SALT_BYTES = 24; public static final int HASH_ITERATIONS = 1; public static String computeSHA256(String password) { MessageDigest messagDigest = null; String saltedPassword = null; SecureRandom random = new SecureRandom(); byte[] salt = new byte[SALT_BYTES]; random.nextBytes(salt); saltedPassword = salt + password; try { messagDigest = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } messagDigest.update(saltedPassword.getBytes()); byte finalHash[] = messagDigest.digest(); return HASH_ITERATIONS + ":" + toHex(salt) + ":" + toHex(finalHash); } public static String hmacSha1(String value, byte[] key) { try { // Get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1"); // Get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); // Compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(value.getBytes()); // Convert raw bytes to Hex byte[] hexBytes = new Hex().encode(rawHmac); // Covert array of Hex bytes to a String return new String(hexBytes, "UTF-8"); } catch (Exception e) { throw new RuntimeException(e); } } public static String toHex(byte[] array) { BigInteger bi = new BigInteger(1, array); String hex = bi.toString(16); int paddingLength = (array.length * 2) - hex.length(); if (paddingLength > 0) return String.format("%0" + paddingLength + "d", 0) + hex; else return hex; } public static byte[] fromHex(String hex) { byte[] binary = new byte[hex.length() / 2]; for (int i = 0; i < binary.length; i++) { binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); } return binary; } }