get File Mac Encrypt - Android java.security

Android examples for java.security:MAC

Description

get File Mac Encrypt

Demo Code


//package com.java2s;
import android.annotation.SuppressLint;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Main {

    public static String getFileMacEncrypt(File file, String algorithm,
            String keyString) throws IOException {
        SecretKey key = generateHmacKey(keyString, algorithm);
        return getFileMacEncrypt(file, key);
    }//  w w w.  ja va  2  s. c  o m

    public static String getFileMacEncrypt(File file, SecretKey key)
            throws IOException {
        String algorithm = key.getAlgorithm();
        Mac mac = null;
        try {
            mac = Mac.getInstance(algorithm);
            mac.init(key);
            FileInputStream in = new FileInputStream(file);
            byte[] buffer = new byte[1024 * 1024];
            int len = 0;
            while ((len = in.read(buffer)) > 0) {
                mac.update(buffer, 0, len);
            }
            in.close();
            return bytes2String(mac.doFinal());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

    @SuppressLint("TrulyRandom")
    public static SecretKey generateHmacKey(String algorithm) {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
            SecretKey key = keyGenerator.generateKey();
            return key;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static SecretKey generateHmacKey(String keyString,
            String algorithm) {
        SecretKey key = new SecretKeySpec(keyString.getBytes(), algorithm);
        return key;
    }

    public static String bytes2String(byte digest[]) {
        String str = "";
        String tempStr = "";
        for (int i = 0; i < digest.length; i++) {
            tempStr = (Integer.toHexString(digest[i] & 0xff));
            if (tempStr.length() == 1) {
                str = str + "0" + tempStr;
            } else {
                str += tempStr;
            }
        }
        return str;
    }
}

Related Tutorials