derive Sync Hmac Key - Android java.security

Android examples for java.security:Key

Description

derive Sync Hmac Key

Demo Code


import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.security.*;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.regex.Pattern;

public class Main{
    private static final byte[] HMAC_INPUT = WeaveUtil
            .toAsciiBytes("Sync-AES_256_CBC-HMAC256");
    private static final WeaveCryptoUtil sm_instance = new WeaveCryptoUtil();
    public static byte[] deriveSyncHmacKey(byte[] secretBytes,
            byte[] bkbytes, String username)
            throws GeneralSecurityException {
        int keySizeInBytes = 256 / 8;
        Mac hMac = Mac.getInstance("HMACSHA256");

        byte[] state = new byte[hMac.getMacLength()];
        SecretKeySpec param = new SecretKeySpec(secretBytes, "SHA256");
        hMac.init(param);//from w ww.j  a  v a 2s .  c o  m
        hMac.update(bkbytes);
        //    hMac.update(WeaveUtil.toAsciiBytes(bkstr));
        hMac.update(HMAC_INPUT);
        hMac.update(WeaveUtil.toAsciiBytes(username));
        hMac.update((byte) 0x2);
        hMac.doFinal(state, 0);
        byte[] retval = new byte[keySizeInBytes];
        System.arraycopy(state, 0, retval, 0, keySizeInBytes);
        return retval;
    }
    public static WeaveCryptoUtil getInstance() {
        return sm_instance;
    }
}

Related Tutorials