Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 Copyright 2014 GhanaianFramework.
    
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
    
 http://www.apache.org/licenses/LICENSE-2.0
    
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import android.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class Main {
    private final static String KEY_ENCODING = "UTF-8";
    private final static String KEY_HASH_SHA1 = "HmacSHA1";

    /**
     *  
     * @param s
     * @param keyString
     * @return
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public static String sha1(String s, String keyString)
            throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        Mac mac = getMac(keyString, KEY_HASH_SHA1);
        byte[] bytes = mac.doFinal(s.getBytes("UTF-8"));
        return new String(Base64.encodeToString(bytes, 0));
    }

    /**
     *
     * @param key
     * @param algo
     * @return
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    static Mac getMac(String key, String algo)
            throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(KEY_ENCODING), algo);
        Mac mac = Mac.getInstance(algo);
        mac.init(secretKeySpec);
        return mac;
    }
}