Java Examples for org.bouncycastle.crypto.macs.HMac

The following java examples will help you to understand the usage of org.bouncycastle.crypto.macs.HMac. These source code samples are taken from different open source projects.

Example 1
Project: java_security-master  File: HMACTest.java View source code
// 用bouncy castle实现:
public static void bcHmacMD5() {
    HMac hmac = new HMac(new MD5Digest());
    // 必须是16进制的字符,长度必须是2的�数
    hmac.init(new KeyParameter(org.bouncycastle.util.encoders.Hex.decode("123456789abcde")));
    hmac.update(src.getBytes(), 0, src.getBytes().length);
    // 执行摘�
    byte[] hmacMD5Bytes = new byte[hmac.getMacSize()];
    hmac.doFinal(hmacMD5Bytes, 0);
    System.out.println("bc hmacMD5:" + org.bouncycastle.util.encoders.Hex.toHexString(hmacMD5Bytes));
}
Example 2
Project: totp-me-master  File: TOTPMIDlet.java View source code
/**
	 * Handles command actions from all forms.
	 * 
	 * @see javax.microedition.lcdui.CommandListener#commandAction(javax.microedition.lcdui.Command,
	 *      javax.microedition.lcdui.Displayable)
	 */
public void commandAction(Command aCmd, Displayable aDisp) {
    if (DEBUG && aCmd != null) {
        debug("Options - Command action: " + aCmd.getLabel());
    }
    final Display display = Display.getDisplay(this);
    if (aDisp == fConfirm) {
        if (aCmd == cmdOK) {
            removeProfile(listProfiles.getSelectedIndex());
        }
        display.setCurrent(listProfiles);
        return;
    }
    if (aCmd == cmdOK) {
        final String warning = validateInput();
        if (warning.length() == 0) {
            siProfile.setText(tfProfile.getString());
            final int algorithmIdx = chgHmacAlgorithm.getSelectedIndex();
            final byte[] secretKey = base32Decode(tfSecret.getString());
            HMac newHmac = null;
            if (secretKey != null) {
                Digest digest = null;
                if (SHA1.equals(HMAC_ALGORITHMS[algorithmIdx])) {
                    digest = new SHA1Digest();
                } else if (SHA256.equals(HMAC_ALGORITHMS[algorithmIdx])) {
                    digest = new SHA256Digest();
                } else if (SHA512.equals(HMAC_ALGORITHMS[algorithmIdx])) {
                    digest = new SHA512Digest();
                }
                newHmac = new HMac(digest);
                newHmac.init(new KeyParameter(secretKey));
            }
            setHMac(newHmac);
            refreshTokenTask.run();
            display.setCurrent(fMain);
            if (aDisp != null)
                save();
            reorderProfiles();
        } else {
            displayAlert("Invalid input:\n" + warning, fOptions);
        }
    } else if (aCmd == cmdGenerator) {
        final byte[] key = base32Decode(tfSecret.getString());
        // set current key
        siKeyHex.setText(key == null ? "" : toHexString(key, 0, key.length));
        siKeyBase32.setText(base32Encode(key));
        display.setCurrent(fGenerator);
    } else if (aCmd == cmdProfiles) {
        display.setCurrent(listProfiles);
    } else if (aCmd == cmdAddProfile) {
        final Calendar cal = Calendar.getInstance();
        // use date-time as generated profile name YYYYMMDD-HHMMSS
        final String profileName = cal.get(Calendar.YEAR) + zeroLeftPad(cal.get(Calendar.MONTH) + 1, 2) + zeroLeftPad(cal.get(Calendar.DAY_OF_MONTH), 2) + "-" + zeroLeftPad(cal.get(Calendar.HOUR_OF_DAY), 2) + zeroLeftPad(cal.get(Calendar.MINUTE), 2) + zeroLeftPad(cal.get(Calendar.SECOND), 2);
        if (DEBUG)
            debug("Creating profile" + profileName);
        int newPos = 0;
        while (newPos < listProfiles.size() && profileName.compareTo(listProfiles.getString(newPos)) > 0) {
            newPos++;
        }
        listProfiles.insert(newPos, profileName, null);
        listProfiles.setSelectedIndex(newPos, true);
        int[] newRecIds = new int[recordIds.length + 1];
        System.arraycopy(recordIds, 0, newRecIds, 0, newPos);
        System.arraycopy(recordIds, newPos, newRecIds, newPos + 1, recordIds.length - newPos);
        recordIds = newRecIds;
        final byte[] profileConfig = getProfileConfig(profileName, EMPTY_BYTE_ARRAY, DEFAULT_TIMESTEP, DEFAULT_HMAC_ALG_IDX, DEFAULT_DIGITS, DEFAULT_DELTA);
        recordIds[newPos] = addProfileToRecordStore(profileConfig);
    } else if (aDisp == listProfiles && aCmd == List.SELECT_COMMAND) {
        if (listProfiles.getSelectedIndex() >= 0)
            loadSelectedProfile();
    } else if (aCmd == cmdRemoveProfile) {
        switch(listProfiles.size()) {
            case 0:
                displayAlert("There is no profile to delete.", listProfiles);
                break;
            case 1:
                displayAlert("You can't remove the last profile.", listProfiles);
                break;
            default:
                if (listProfiles.getSelectedIndex() >= 0) {
                    siConfirm.setText("Do you really want to delete profile " + listProfiles.getString(listProfiles.getSelectedIndex()) + "?");
                    display.setCurrent(fConfirm);
                }
                break;
        }
    } else if (aCmd == cmdNewKey) {
        final byte[] secretKey = generateNewKey();
        siKeyHex.setText(toHexString(secretKey, 0, secretKey.length));
        siKeyBase32.setText(base32Encode(secretKey));
        tfSecret.setString(siKeyBase32.getText());
    } else if (aCmd == cmdGeneratorOK) {
        display.setCurrent(fOptions);
    } else if (aCmd == cmdOptions) {
        display.setCurrent(fOptions);
    } else if (aCmd == cmdReset) {
        setHMac(null);
        gauValidity.setMaxValue(INDEFINITE);
        gauValidity.setValue(IDLE);
        tfSecret.setString(base32Encode(DEFAULT_SECRET));
        tfTimeStep.setString(Integer.toString(DEFAULT_TIMESTEP));
        tfDigits.setString(Integer.toString(DEFAULT_DIGITS));
        chgHmacAlgorithm.setSelectedIndex(DEFAULT_HMAC_ALG_IDX, true);
        tfDelta.setString(Long.toString(DEFAULT_DELTA));
        tfProfile.setString(listProfiles.getString(listProfiles.getSelectedIndex()));
    } else if (aCmd == cmdExit) {
        destroyApp(false);
    }
    cachedCounter = INVALID_COUNTER;
}
Example 3
Project: bc-java-master  File: TlsUtils.java View source code
static void hmac_hash(Digest digest, byte[] secret, byte[] seed, byte[] out) {
    HMac mac = new HMac(digest);
    mac.init(new KeyParameter(secret));
    byte[] a = seed;
    int size = digest.getDigestSize();
    int iterations = (out.length + size - 1) / size;
    byte[] buf = new byte[mac.getMacSize()];
    byte[] buf2 = new byte[mac.getMacSize()];
    for (int i = 0; i < iterations; i++) {
        mac.update(a, 0, a.length);
        mac.doFinal(buf, 0);
        a = buf;
        mac.update(a, 0, a.length);
        mac.update(seed, 0, seed.length);
        mac.doFinal(buf2, 0);
        System.arraycopy(buf2, 0, out, (size * i), Math.min(size, out.length - (size * i)));
    }
}
Example 4
Project: dc---master  File: TlsUtils.java View source code
private static void hmac_hash(Digest digest, byte[] secret, byte[] seed, byte[] out) {
    HMac mac = new HMac(digest);
    KeyParameter param = new KeyParameter(secret);
    byte[] a = seed;
    int size = digest.getDigestSize();
    int iterations = (out.length + size - 1) / size;
    byte[] buf = new byte[mac.getMacSize()];
    byte[] buf2 = new byte[mac.getMacSize()];
    for (int i = 0; i < iterations; i++) {
        mac.init(param);
        mac.update(a, 0, a.length);
        mac.doFinal(buf, 0);
        a = buf;
        mac.init(param);
        mac.update(a, 0, a.length);
        mac.update(seed, 0, seed.length);
        mac.doFinal(buf2, 0);
        System.arraycopy(buf2, 0, out, (size * i), Math.min(size, out.length - (size * i)));
    }
}
Example 5
Project: gupa-j2me-midlet-master  File: HMACSHA1Signature.java View source code
public String getSignature() {
    try {
        HMac m = new HMac(new SHA1Digest());
        m.init(new KeyParameter(key.getBytes("UTF-8")));
        byte[] bytes = message.getBytes("UTF-8");
        m.update(bytes, 0, bytes.length);
        byte[] mac = new byte[m.getMacSize()];
        m.doFinal(mac, 0);
        signature = new String(Util.base64Encode(mac));
        // debug
        System.out.println("mac alg: " + m.getAlgorithmName());
        System.out.println("dig alg: " + m.getUnderlyingDigest().getAlgorithmName());
        System.out.println("key: " + key);
        System.out.println("message: " + message);
        System.out.println("unencoded: " + new String(mac));
        System.out.println("sig: " + signature);
    } catch (java.io.UnsupportedEncodingException e) {
        ;
    } catch (Exception e) {
        ;
    }
    return signature;
}
Example 6
Project: irma_future_id-master  File: HMacDRBGTest.java View source code
public void performTest() throws Exception {
    DRBGTestVector[] tests = createTestVectorData();
    for (int i = 0; i != tests.length; i++) {
        DRBGTestVector tv = tests[i];
        byte[] nonce = tv.nonce();
        byte[] personalisationString = tv.personalizationString();
        SP80090DRBG d = new HMacSP800DRBG(new HMac(tv.getDigest()), tv.securityStrength(), tv.entropySource(), personalisationString, nonce);
        byte[] output = new byte[tv.expectedValue(0).length];
        d.generate(output, tv.additionalInput(0), tv.predictionResistance());
        byte[] expected = tv.expectedValue(0);
        if (!areEqual(expected, output)) {
            fail("Test #" + (i + 1) + ".1 failed, expected " + new String(Hex.encode(tv.expectedValue(0))) + " got " + new String(Hex.encode(output)));
        }
        output = new byte[tv.expectedValue(0).length];
        d.generate(output, tv.additionalInput(1), tv.predictionResistance());
        expected = tv.expectedValue(1);
        if (!areEqual(expected, output)) {
            fail("Test #" + (i + 1) + ".2 failed, expected " + new String(Hex.encode(tv.expectedValue(1))) + " got " + new String(Hex.encode(output)));
        }
    }
    // Exception tests
    //
    SP80090DRBG d;
    try {
        d = new HMacSP800DRBG(new HMac(new SHA256Digest()), 256, new SHA256EntropyProvider().get(128), null, null);
        fail("no exception thrown");
    } catch (IllegalArgumentException e) {
        if (!e.getMessage().equals("Not enough entropy for security strength required")) {
            fail("Wrong exception", e);
        }
    }
}
Example 7
Project: j2me-oauth-master  File: HMACSHA1Signature.java View source code
public String getSignature() {
    try {
        HMac m = new HMac(new SHA1Digest());
        m.init(new KeyParameter(key.getBytes("UTF-8")));
        byte[] bytes = message.getBytes("UTF-8");
        m.update(bytes, 0, bytes.length);
        byte[] mac = new byte[m.getMacSize()];
        m.doFinal(mac, 0);
        signature = new String(Util.base64Encode(mac));
        // debug
        System.out.println("mac alg: " + m.getAlgorithmName());
        System.out.println("dig alg: " + m.getUnderlyingDigest().getAlgorithmName());
        System.out.println("key: " + key);
        System.out.println("message: " + message);
        System.out.println("unencoded: " + new String(mac));
        System.out.println("sig: " + signature);
    } catch (java.io.UnsupportedEncodingException e) {
        ;
    } catch (Exception e) {
        ;
    }
    return signature;
}
Example 8
Project: modrupal-master  File: AuthInterface.java View source code
/**
     * Generates a HMAC SHA256 hash for the given method using
     * the current authentication data.
     * 
     * @param method the method to call
     * @return the hashed authentication string
     */
public String get_hash(String method) {
    this.timestamp = Long.toString(getTime());
    this.nonce = getRandomString();
    this.method = method;
    HMac hmac = new HMac(new SHA256Digest());
    byte[] resBuf = new byte[hmac.getMacSize()];
    //byte[] keyBytes = Hex.decode(api_key);
    byte[] keyBytes = api_key.getBytes();
    hmac.init(new KeyParameter(keyBytes));
    String msg = getMessage();
    byte[] m = msg.getBytes();
    hmac.update(m, 0, m.length);
    hmac.doFinal(resBuf, 0);
    this.hash = new String(Hex.encode(resBuf));
    //this.hash = new String(resBuf);
    return this.hash;
}
Example 9
Project: openiam-idm-master  File: SHA2Hash.java View source code
/* (non-Javadoc)
	 * @see org.openiam.util.encrypt.HashDigest#hash(java.lang.String)
	 */
public byte[] hash(String msg) {
    // get instance of the SHA Message Digest object.
    HMac hmac = new HMac(new SHA256Digest());
    byte[] result = new byte[hmac.getMacSize()];
    byte[] msgAry = msg.getBytes();
    if (key == null) {
        readKey();
    }
    KeyParameter kp = new KeyParameter(key);
    hmac.init(kp);
    hmac.update(msgAry, 0, msgAry.length);
    hmac.doFinal(result, 0);
    return result;
}
Example 10
Project: SawGoo_iappli-master  File: HMACSHA1Signature.java View source code
public String getSignature() {
    try {
        HMac m = new HMac(new SHA1Digest());
        m.init(new KeyParameter(key.getBytes("UTF-8")));
        byte[] bytes = message.getBytes("UTF-8");
        m.update(bytes, 0, bytes.length);
        byte[] mac = new byte[m.getMacSize()];
        m.doFinal(mac, 0);
        signature = new String(Util.base64Encode(mac));
        // debug
        System.out.println("mac alg: " + m.getAlgorithmName());
        System.out.println("dig alg: " + m.getUnderlyingDigest().getAlgorithmName());
        System.out.println("key: " + key);
        System.out.println("message: " + message);
        System.out.println("unencoded: " + new String(mac));
        System.out.println("sig: " + signature);
    } catch (UnsupportedEncodingException e) {
        ;
    } catch (Exception e) {
        ;
    }
    return signature;
}
Example 11
Project: TinyTravelTracker-master  File: TlsUtils.java View source code
static void hmac_hash(Digest digest, byte[] secret, byte[] seed, byte[] out) {
    HMac mac = new HMac(digest);
    mac.init(new KeyParameter(secret));
    byte[] a = seed;
    int size = digest.getDigestSize();
    int iterations = (out.length + size - 1) / size;
    byte[] buf = new byte[mac.getMacSize()];
    byte[] buf2 = new byte[mac.getMacSize()];
    for (int i = 0; i < iterations; i++) {
        mac.update(a, 0, a.length);
        mac.doFinal(buf, 0);
        a = buf;
        mac.update(a, 0, a.length);
        mac.update(seed, 0, seed.length);
        mac.doFinal(buf2, 0);
        System.arraycopy(buf2, 0, out, (size * i), Math.min(size, out.length - (size * i)));
    }
}
Example 12
Project: fred-master  File: HMACTest.java View source code
// ant -Dtest.skip=false -Dtest.class=freenet.crypt.HMACTest -Dtest.benchmark=true unit
public void testBenchmark() {
    if (!TestProperty.BENCHMARK) {
        return;
    }
    int count = 0;
    System.out.println("We're getting ready to benchmark HMACs");
    Random r = new Random(0xBBBBBBBB);
    for (int len = 8; len <= 32768; len *= 4) {
        byte[] plaintext = new byte[len];
        r.nextBytes(plaintext);
        System.out.println("plaintext len " + len);
        int ITERATIONS = 10000000 / len;
        long t1 = System.currentTimeMillis();
        for (int i = 0; i < ITERATIONS; i++) {
            byte[] r1 = HMAC_legacy.macWithSHA256(knownKey, plaintext, 32);
            for (int j = 0; j < r1.length; j++) {
                count += r1[j];
            }
        }
        long legacyLength = System.currentTimeMillis() - t1;
        t1 = System.currentTimeMillis();
        for (int i = 0; i < ITERATIONS; i++) {
            byte[] r1 = HMAC.macWithSHA256(knownKey, plaintext);
            for (int j = 0; j < r1.length; j++) {
                count += r1[j];
            }
        }
        long currentLength = System.currentTimeMillis() - t1;
        t1 = System.currentTimeMillis();
        for (int i = 0; i < ITERATIONS; i++) {
            byte[] r1 = new byte[32];
            HMac hmac = new HMac(new SHA256Digest());
            KeyParameter kp = new KeyParameter(knownKey);
            hmac.init(kp);
            hmac.update(plaintext, 0, plaintext.length);
            hmac.doFinal(r1, 0);
            for (int j = 0; j < r1.length; j++) {
                count += r1[j];
            }
        }
        long BCLength = System.currentTimeMillis() - t1;
        System.out.println("Legacy HMAC took " + TimeUtil.formatTime(legacyLength, 6, true));
        System.out.println("Current HMAC took " + TimeUtil.formatTime(currentLength, 6, true));
        System.out.println("BC HMAC took " + TimeUtil.formatTime(BCLength, 6, true));
    }
}
Example 13
Project: android-rackspacecloud-master  File: BouncyCastleEncryptionService.java View source code
public byte[] hmac(String toEncode, byte[] key, Digest digest) {
    HMac hmac = new HMac(digest);
    byte[] resBuf = new byte[hmac.getMacSize()];
    byte[] plainBytes = Utils.encodeString(toEncode);
    byte[] keyBytes = key;
    hmac.init(new KeyParameter(keyBytes));
    hmac.update(plainBytes, 0, plainBytes.length);
    hmac.doFinal(resBuf, 0);
    return resBuf;
}
Example 14
Project: Android-Shapeways-master  File: Request.java View source code
/**
	 * Generate HMAC-SHA1 for message
	 * 
	 * @param key
	 * @param message
	 * @return
	 * @throws Exception
	 */
private static String generateHmac(String key, String message) throws Exception {
    Log.d(LOG_TAG, "generateHmac: " + key + "=" + message);
    byte[] keyBytes = key.getBytes(ShapewaysClient.ENCODING);
    byte[] data = message.getBytes(ShapewaysClient.ENCODING);
    HMac macProvider = new HMac(new SHA1Digest());
    macProvider.init(new KeyParameter(keyBytes));
    macProvider.reset();
    macProvider.update(data, 0, data.length);
    byte[] output = new byte[macProvider.getMacSize()];
    macProvider.doFinal(output, 0);
    byte[] hmac = Base64.encode(output);
    return new String(hmac).replaceAll("\r\n", "");
}
Example 15
Project: atlas-lb-master  File: JDKKeyStore.java View source code
public void engineLoad(InputStream stream, char[] password) throws IOException {
    table.clear();
    if (// just initialising
    stream == null) {
        return;
    }
    DataInputStream dIn = new DataInputStream(stream);
    int version = dIn.readInt();
    if (version != STORE_VERSION) {
        if (version != 0) {
            throw new IOException("Wrong version of key store.");
        }
    }
    byte[] salt = new byte[dIn.readInt()];
    dIn.readFully(salt);
    int iterationCount = dIn.readInt();
    //
    // we only do an integrity check if the password is provided.
    //
    HMac hMac = new HMac(new SHA1Digest());
    if (password != null && password.length != 0) {
        byte[] passKey = PBEParametersGenerator.PKCS12PasswordToBytes(password);
        PBEParametersGenerator pbeGen = new PKCS12ParametersGenerator(new SHA1Digest());
        pbeGen.init(passKey, salt, iterationCount);
        CipherParameters macParams = pbeGen.generateDerivedMacParameters(hMac.getMacSize());
        Arrays.fill(passKey, (byte) 0);
        hMac.init(macParams);
        MacInputStream mIn = new MacInputStream(dIn, hMac);
        loadStore(mIn);
        // Finalise our mac calculation
        byte[] mac = new byte[hMac.getMacSize()];
        hMac.doFinal(mac, 0);
        // TODO Should this actually be reading the remainder of the stream?
        // Read the original mac from the stream
        byte[] oldMac = new byte[hMac.getMacSize()];
        dIn.readFully(oldMac);
        if (!Arrays.constantTimeAreEqual(mac, oldMac)) {
            table.clear();
            throw new IOException("KeyStore integrity check failed.");
        }
    } else {
        loadStore(dIn);
        // TODO Should this actually be reading the remainder of the stream?
        // Parse the original mac from the stream too
        byte[] oldMac = new byte[hMac.getMacSize()];
        dIn.readFully(oldMac);
    }
}
Example 16
Project: cachewolf-master  File: TlsUtils.java View source code
private static void hmac_hash(Digest digest, byte[] secret, byte[] seed, byte[] out) {
    HMac mac = new HMac(digest);
    KeyParameter param = new KeyParameter(secret);
    byte[] a = seed;
    int size = digest.getDigestSize();
    int iterations = (out.length + size - 1) / size;
    byte[] buf = new byte[mac.getMacSize()];
    byte[] buf2 = new byte[mac.getMacSize()];
    for (int i = 0; i < iterations; i++) {
        mac.init(param);
        mac.update(a, 0, a.length);
        mac.doFinal(buf, 0);
        a = buf;
        mac.init(param);
        mac.update(a, 0, a.length);
        mac.update(seed, 0, seed.length);
        mac.doFinal(buf2, 0);
        System.arraycopy(buf2, 0, out, (size * i), Math.min(size, out.length - (size * i)));
    }
}
Example 17
Project: jcardsim-master  File: SymmetricSignatureImpl.java View source code
public void init(Key theKey, byte theMode, byte[] bArray, short bOff, short bLen) throws CryptoException {
    if (theKey == null) {
        CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY);
    }
    if (!theKey.isInitialized()) {
        CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY);
    }
    if (!(theKey instanceof SymmetricKeyImpl)) {
        CryptoException.throwIt(CryptoException.ILLEGAL_VALUE);
    }
    CipherParameters cipherParams = null;
    BlockCipher cipher = ((SymmetricKeyImpl) theKey).getCipher();
    if (bArray == null) {
        cipherParams = ((SymmetricKeyImpl) theKey).getParameters();
    } else {
        if (bLen != cipher.getBlockSize()) {
            CryptoException.throwIt(CryptoException.ILLEGAL_VALUE);
        }
        cipherParams = new ParametersWithIV(((SymmetricKeyImpl) theKey).getParameters(), bArray, bOff, bLen);
    }
    switch(algorithm) {
        case ALG_DES_MAC4_NOPAD:
            engine = new CBCBlockCipherMac(cipher, 32, null);
            break;
        case ALG_DES_MAC8_NOPAD:
            engine = new CBCBlockCipherMac(cipher, 64, null);
            break;
        case ALG_DES_MAC4_ISO9797_M1:
            engine = new CBCBlockCipherMac(cipher, 32, new ZeroBytePadding());
            break;
        case ALG_DES_MAC8_ISO9797_M1:
            engine = new CBCBlockCipherMac(cipher, 64, new ZeroBytePadding());
            break;
        case ALG_DES_MAC4_ISO9797_M2:
            engine = new CBCBlockCipherMac(cipher, 32, new ISO7816d4Padding());
            break;
        case ALG_DES_MAC8_ISO9797_M2:
            engine = new CBCBlockCipherMac(cipher, 64, new ISO7816d4Padding());
            break;
        case ALG_DES_MAC8_ISO9797_1_M2_ALG3:
            engine = new ISO9797Alg3Mac(new DESEngine(), 64, new ISO7816d4Padding());
            break;
        case ALG_DES_MAC4_PKCS5:
            engine = new CBCBlockCipherMac(cipher, 32, new PKCS7Padding());
            break;
        case ALG_DES_MAC8_PKCS5:
            engine = new CBCBlockCipherMac(cipher, 64, new PKCS7Padding());
            break;
        case ALG_AES_MAC_128_NOPAD:
            engine = new CBCBlockCipherMac(cipher, 128, null);
            break;
        case ALG_AES_CMAC_128:
            engine = new CMac(cipher, 128);
            break;
        case ALG_HMAC_SHA1:
            engine = new HMac(new SHA1Digest());
            break;
        case ALG_HMAC_SHA_256:
            engine = new HMac(new SHA256Digest());
            break;
        case ALG_HMAC_SHA_384:
            engine = new HMac(new SHA384Digest());
            break;
        case ALG_HMAC_SHA_512:
            engine = new HMac(new SHA512Digest());
            break;
        case ALG_HMAC_MD5:
            engine = new HMac(new MD5Digest());
            break;
        case ALG_HMAC_RIPEMD160:
            engine = new HMac(new RIPEMD160Digest());
            break;
        default:
            CryptoException.throwIt(CryptoException.NO_SUCH_ALGORITHM);
            break;
    }
    engine.init(cipherParams);
    isInitialized = true;
}
Example 18
Project: jradius-master  File: TlsUtils.java View source code
private static void hmac_hash(Digest digest, byte[] secret, byte[] seed, byte[] out) {
    HMac mac = new HMac(digest);
    KeyParameter param = new KeyParameter(secret);
    byte[] a = seed;
    int size = digest.getDigestSize();
    int iterations = (out.length + size - 1) / size;
    byte[] buf = new byte[mac.getMacSize()];
    byte[] buf2 = new byte[mac.getMacSize()];
    for (int i = 0; i < iterations; i++) {
        mac.init(param);
        mac.update(a, 0, a.length);
        mac.doFinal(buf, 0);
        a = buf;
        mac.init(param);
        mac.update(a, 0, a.length);
        mac.update(seed, 0, seed.length);
        mac.doFinal(buf2, 0);
        System.arraycopy(buf2, 0, out, (size * i), Math.min(size, out.length - (size * i)));
    }
}
Example 19
Project: trsst-master  File: Crypto.java View source code
private static byte[] _cryptIES(byte[] input, Key recipient, boolean forEncryption) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    IESCipher cipher = new IESCipher(new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA256Digest()), new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()))));
    cipher.engineInit(forEncryption ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, recipient, new SecureRandom());
    return cipher.engineDoFinal(input, 0, input.length);
}
Example 20
Project: twim-master  File: XAuth.java View source code
public String getSignature(String message, String key) {
    try {
        HMac m = new HMac(new SHA1Digest());
        m.init(new KeyParameter(key.getBytes("UTF-8")));
        byte[] bytes = message.getBytes("UTF-8");
        m.update(bytes, 0, bytes.length);
        byte[] mac = new byte[m.getMacSize()];
        m.doFinal(mac, 0);
        String signature = new Base64().encode(mac);
        return signature;
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }
    return null;
}
Example 21
Project: xwiki-social-login-master  File: PBKDF2KeyDerivationFunction.java View source code
/**
     * Generate the PBKDF2 derived key.
     * This is an implementation of PBKDF2(P, S, c, dkLen) defined in http://www.ietf.org/rfc/rfc2898.txt
     *
     * @param password the user supplied password expressed as a byte array.
     * @param salt the random salt to add to the password before hashing.
     * @param iterationCount the number of iterations which the internal function (F) should run.
     * @param derivedKeyLength the number of bytes of length the derived key should be (dkLen)
     * @return a byte array of length derivedKeyLength containing data derived from the password and salt.
     *         suitable for a key.
     */
public synchronized byte[] generateDerivedKey(final byte[] password, final byte[] salt, final int iterationCount, final int derivedKeyLength) {
    // If this was deserialized, then the hmac must be loaded.
    if (this.hMac == null) {
        try {
            this.hMac = new HMac((Digest) Class.forName(this.digestClassName).newInstance());
            this.state = new byte[this.hMac.getMacSize()];
        } catch (Exception e) {
            throw new RuntimeException("Apparently this object was serialized when a digest (" + this.digestClassName + ") was available which is not available now.", e);
        }
    }
    try {
        int hLen = hMac.getMacSize();
        // "Let l be the number of hLen-octet blocks in the derived key" (rfc2898)
        int numberOfBlocks = (derivedKeyLength + hLen - 1) / hLen;
        final byte[] currentIterationAsByteArray = new byte[4];
        final byte[] key = new byte[numberOfBlocks * hLen];
        for (int i = 1; i <= numberOfBlocks; i++) {
            this.integerToByteArray(i, currentIterationAsByteArray);
            this.functionF(password, salt, iterationCount, currentIterationAsByteArray, key, (i - 1) * hLen);
        }
        // Usually the key ends up being longer than the desired key length so it must be truncated
        byte[] out = new byte[derivedKeyLength];
        System.arraycopy(key, 0, out, 0, derivedKeyLength);
        return out;
    } finally {
        // Set state to 0's in order to prevent the last state being read later.
        System.arraycopy(new byte[this.state.length], 0, this.state, 0, this.state.length);
    }
}
Example 22
Project: authenticator-master  File: AuthenticatorScreen.java View source code
/**
   * Computes the one-time PIN given the secret key.
   * 
   * @param secret
   *          the secret key
   * @return the PIN
   * @throws GeneralSecurityException
   * @throws DecodingException
   *           If the key string is improperly encoded.
   */
public static String computePin(String secret, Long counter) {
    try {
        final byte[] keyBytes = Base32String.decode(secret);
        Mac mac = new HMac(new SHA1Digest());
        mac.init(new KeyParameter(keyBytes));
        PasscodeGenerator pcg = new PasscodeGenerator(mac);
        if (counter == null) {
            // time-based totp
            return pcg.generateTimeoutCode();
        } else {
            // counter-based hotp
            return pcg.generateResponseCode(counter.longValue());
        }
    } catch (RuntimeException e) {
        return "General security exception";
    } catch (DecodingException e) {
        return "Decoding exception";
    }
}
Example 23
Project: google-authenticator-master  File: AuthenticatorScreen.java View source code
/**
   * Computes the one-time PIN given the secret key.
   * 
   * @param secret
   *          the secret key
   * @return the PIN
   * @throws GeneralSecurityException
   * @throws DecodingException
   *           If the key string is improperly encoded.
   */
public static String computePin(String secret, Long counter) {
    try {
        final byte[] keyBytes = Base32String.decode(secret);
        Mac mac = new HMac(new SHA1Digest());
        mac.init(new KeyParameter(keyBytes));
        PasscodeGenerator pcg = new PasscodeGenerator(mac);
        if (counter == null) {
            // time-based totp
            return pcg.generateTimeoutCode();
        } else {
            // counter-based hotp
            return pcg.generateResponseCode(counter.longValue());
        }
    } catch (RuntimeException e) {
        return "General security exception";
    } catch (DecodingException e) {
        return "Decoding exception";
    }
}
Example 24
Project: PanBox-master  File: EncRandomAccessFile.java View source code
/**
		 * writes header data to the file
		 * 
		 * @throws FileEncryptionException
		 * @throws IOException
		 * @throws InvalidKeyException
		 * @throws BadPaddingException
		 * @throws IllegalBlockSizeException
		 */
protected synchronized void write() throws FileEncryptionException, IOException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    // check if all necessary data has been set
    if ((getDecryptedFileKey() == null) || (getDecryptedFileKey().getEncoded().length == 0)) {
        throw new FileEncryptionException("Decrypted file key has not been set!");
    }
    if (getShareKeyVersion() < 0) {
        throw new FileEncryptionException("Share key version number has not been set!");
    }
    // if all data have been set, initialize HMac with shareKey
    if (shareKey == null || shareKey.getEncoded().length == 0) {
        throw new FileEncryptionException("Invalid share key in encrypting random access file!");
    } else {
        headerAuthHMac.reset();
        KeyParameter keyParameter = new KeyParameter(shareKey.getEncoded());
        headerAuthHMac.init(keyParameter);
    }
    // encrypt file key
    byte[] tmpencryptedFileKey = new byte[KeyConstants.SYMMETRIC_FILE_KEY_SIZE_BYTES];
    filekeyCipher.init(Cipher.ENCRYPT_MODE, shareKey);
    byte[] t2 = decryptedFileKey.getEncoded();
    if ((t2 == null) || (t2.length != KeyConstants.SYMMETRIC_FILE_KEY_SIZE_BYTES)) {
        throw new FileEncryptionException("Encoded file key null or invalid length!");
    }
    tmpencryptedFileKey = filekeyCipher.doFinal(t2);
    // create output buffer & write header data
    ByteArrayOutputStream bstream = new ByteArrayOutputStream();
    DataOutputStream ostream = new DataOutputStream(bstream);
    ostream.write(PANBOX_FILE_MAGIC);
    ostream.write(PANBOX_FILE_VERSION);
    ostream.writeInt(shareKeyVersion);
    ostream.write(tmpencryptedFileKey);
    if (implementsAuthentication()) {
        if (getFileAuthTag() == null) {
            // if no chunks have been stored yet, the initial file auth
            // tag will be set to zero
            byte[] emptyAuthTag = new byte[AuthTagVerifier.AUTH_TAG_SIZE];
            Arrays.fill(emptyAuthTag, (byte) 0x00);
            ostream.write(emptyAuthTag);
        // setFileAuthTag(null);
        } else {
            ostream.write(fileAuthTag);
        }
    }
    ostream.close();
    // all data have been written to stream, get array
    byte[] header_data = bstream.toByteArray();
    // calculate hmac
    headerAuthHMac.update(header_data, 0, header_data.length);
    headerAuthHMac.doFinal(headerAuthTag, 0);
    // write data and hmac
    long oldpos = backingRandomAccessFile.getFilePointer();
    backingRandomAccessFile.seek(0);
    backingRandomAccessFile.write(header_data);
    backingRandomAccessFile.write(headerAuthTag);
    backingRandomAccessFile.seek(oldpos);
}
Example 25
Project: android_libcore-master  File: JDKKeyStore.java View source code
public void engineLoad(InputStream stream, char[] password) throws IOException {
    table.clear();
    if (// just initialising
    stream == null) {
        return;
    }
    DataInputStream dIn = new DataInputStream(stream);
    int version = dIn.readInt();
    if (version != STORE_VERSION) {
        if (version != 0) {
            throw new IOException("Wrong version of key store.");
        }
    }
    byte[] salt = new byte[dIn.readInt()];
    dIn.readFully(salt);
    int iterationCount = dIn.readInt();
    // BEGIN android-removed
    //         HMac                    hMac = new HMac(new SHA1Digest());
    //         MacInputStream          mIn = new MacInputStream(dIn, hMac);
    //         PBEParametersGenerator  pbeGen = new PKCS12ParametersGenerator(new SHA1Digest());
    // END android-removed
    // BEGIN android-added
    HMac hMac = new HMac(OpenSSLMessageDigest.getInstance("SHA-1"));
    MacInputStream mIn = new MacInputStream(dIn, hMac);
    PBEParametersGenerator pbeGen = new PKCS12ParametersGenerator(OpenSSLMessageDigest.getInstance("SHA-1"));
    // END android-added
    byte[] passKey = PBEParametersGenerator.PKCS12PasswordToBytes(password);
    pbeGen.init(passKey, salt, iterationCount);
    hMac.init(pbeGen.generateDerivedMacParameters(hMac.getMacSize()));
    for (int i = 0; i != passKey.length; i++) {
        passKey[i] = 0;
    }
    loadStore(mIn);
    byte[] mac = new byte[hMac.getMacSize()];
    byte[] oldMac = new byte[hMac.getMacSize()];
    hMac.doFinal(mac, 0);
    for (int i = 0; i != oldMac.length; i++) {
        oldMac[i] = (byte) dIn.read();
    }
    //
    if ((password != null && password.length != 0) && !isSameAs(mac, oldMac)) {
        table.clear();
        throw new IOException("KeyStore integrity check failed.");
    }
}
Example 26
Project: bugvm-master  File: BcKeyStoreSpi.java View source code
public void engineLoad(InputStream stream, char[] password) throws IOException {
    table.clear();
    if (// just initialising
    stream == null) {
        return;
    }
    DataInputStream dIn = new DataInputStream(stream);
    int version = dIn.readInt();
    if (version != STORE_VERSION) {
        if (version != 0 && version != 1) {
            throw new IOException("Wrong version of key store.");
        }
    }
    int saltLength = dIn.readInt();
    if (saltLength <= 0) {
        throw new IOException("Invalid salt detected");
    }
    byte[] salt = new byte[saltLength];
    dIn.readFully(salt);
    int iterationCount = dIn.readInt();
    //
    // we only do an integrity check if the password is provided.
    //
    HMac hMac = new HMac(new SHA1Digest());
    if (password != null && password.length != 0) {
        byte[] passKey = PBEParametersGenerator.PKCS12PasswordToBytes(password);
        PBEParametersGenerator pbeGen = new PKCS12ParametersGenerator(new SHA1Digest());
        pbeGen.init(passKey, salt, iterationCount);
        CipherParameters macParams;
        if (version != 2) {
            macParams = pbeGen.generateDerivedMacParameters(hMac.getMacSize());
        } else {
            macParams = pbeGen.generateDerivedMacParameters(hMac.getMacSize() * 8);
        }
        Arrays.fill(passKey, (byte) 0);
        hMac.init(macParams);
        MacInputStream mIn = new MacInputStream(dIn, hMac);
        loadStore(mIn);
        // Finalise our mac calculation
        byte[] mac = new byte[hMac.getMacSize()];
        hMac.doFinal(mac, 0);
        // TODO Should this actually be reading the remainder of the stream?
        // Read the original mac from the stream
        byte[] oldMac = new byte[hMac.getMacSize()];
        dIn.readFully(oldMac);
        if (!Arrays.constantTimeAreEqual(mac, oldMac)) {
            table.clear();
            throw new IOException("KeyStore integrity check failed.");
        }
    } else {
        loadStore(dIn);
        // TODO Should this actually be reading the remainder of the stream?
        // Parse the original mac from the stream too
        byte[] oldMac = new byte[hMac.getMacSize()];
        dIn.readFully(oldMac);
    }
}
Example 27
Project: open-mika-master  File: JDKKeyStore.java View source code
public void engineLoad(InputStream stream, char[] password) throws IOException {
    table.clear();
    if (// just initialising
    stream == null) {
        return;
    }
    DataInputStream dIn = new DataInputStream(stream);
    int version = dIn.readInt();
    if (version != STORE_VERSION) {
        if (version != 0) {
            throw new IOException("Wrong version of key store.");
        }
    }
    byte[] salt = new byte[dIn.readInt()];
    dIn.readFully(salt);
    int iterationCount = dIn.readInt();
    // BEGIN android-removed
    //         HMac                    hMac = new HMac(new SHA1Digest());
    //         MacInputStream          mIn = new MacInputStream(dIn, hMac);
    //         PBEParametersGenerator  pbeGen = new PKCS12ParametersGenerator(new SHA1Digest());
    // END android-removed
    // BEGIN android-added
    HMac hMac = new HMac(OpenSSLMessageDigest.getInstance("SHA-1"));
    MacInputStream mIn = new MacInputStream(dIn, hMac);
    PBEParametersGenerator pbeGen = new PKCS12ParametersGenerator(OpenSSLMessageDigest.getInstance("SHA-1"));
    // END android-added
    byte[] passKey = PBEParametersGenerator.PKCS12PasswordToBytes(password);
    pbeGen.init(passKey, salt, iterationCount);
    hMac.init(pbeGen.generateDerivedMacParameters(hMac.getMacSize()));
    for (int i = 0; i != passKey.length; i++) {
        passKey[i] = 0;
    }
    loadStore(mIn);
    byte[] mac = new byte[hMac.getMacSize()];
    byte[] oldMac = new byte[hMac.getMacSize()];
    hMac.doFinal(mac, 0);
    for (int i = 0; i != oldMac.length; i++) {
        oldMac[i] = (byte) dIn.read();
    }
    //
    if ((password != null && password.length != 0) && !isSameAs(mac, oldMac)) {
        table.clear();
        throw new IOException("KeyStore integrity check failed.");
    }
}
Example 28
Project: QRCode-APG-master  File: JDKKeyStore.java View source code
public void engineLoad(InputStream stream, char[] password) throws IOException {
    table.clear();
    if (// just initialising
    stream == null) {
        return;
    }
    DataInputStream dIn = new DataInputStream(stream);
    int version = dIn.readInt();
    if (version != STORE_VERSION) {
        if (version != 0) {
            throw new IOException("Wrong version of key store.");
        }
    }
    byte[] salt = new byte[dIn.readInt()];
    dIn.readFully(salt);
    int iterationCount = dIn.readInt();
    //
    // we only do an integrity check if the password is provided.
    //
    HMac hMac = new HMac(new SHA1Digest());
    if (password != null && password.length != 0) {
        byte[] passKey = PBEParametersGenerator.PKCS12PasswordToBytes(password);
        PBEParametersGenerator pbeGen = new PKCS12ParametersGenerator(new SHA1Digest());
        pbeGen.init(passKey, salt, iterationCount);
        CipherParameters macParams = pbeGen.generateDerivedMacParameters(hMac.getMacSize());
        Arrays.fill(passKey, (byte) 0);
        hMac.init(macParams);
        MacInputStream mIn = new MacInputStream(dIn, hMac);
        loadStore(mIn);
        // Finalise our mac calculation
        byte[] mac = new byte[hMac.getMacSize()];
        hMac.doFinal(mac, 0);
        // TODO Should this actually be reading the remainder of the stream?
        // Read the original mac from the stream
        byte[] oldMac = new byte[hMac.getMacSize()];
        dIn.readFully(oldMac);
        if (!Arrays.constantTimeAreEqual(mac, oldMac)) {
            table.clear();
            throw new IOException("KeyStore integrity check failed.");
        }
    } else {
        loadStore(dIn);
        // TODO Should this actually be reading the remainder of the stream?
        // Parse the original mac from the stream too
        byte[] oldMac = new byte[hMac.getMacSize()];
        dIn.readFully(oldMac);
    }
}
Example 29
Project: robovm-master  File: BcKeyStoreSpi.java View source code
public void engineLoad(InputStream stream, char[] password) throws IOException {
    table.clear();
    if (// just initialising
    stream == null) {
        return;
    }
    DataInputStream dIn = new DataInputStream(stream);
    int version = dIn.readInt();
    if (version != STORE_VERSION) {
        if (version != 0 && version != 1) {
            throw new IOException("Wrong version of key store.");
        }
    }
    int saltLength = dIn.readInt();
    if (saltLength <= 0) {
        throw new IOException("Invalid salt detected");
    }
    byte[] salt = new byte[saltLength];
    dIn.readFully(salt);
    int iterationCount = dIn.readInt();
    //
    // we only do an integrity check if the password is provided.
    //
    HMac hMac = new HMac(new SHA1Digest());
    if (password != null && password.length != 0) {
        byte[] passKey = PBEParametersGenerator.PKCS12PasswordToBytes(password);
        PBEParametersGenerator pbeGen = new PKCS12ParametersGenerator(new SHA1Digest());
        pbeGen.init(passKey, salt, iterationCount);
        CipherParameters macParams;
        if (version != 2) {
            macParams = pbeGen.generateDerivedMacParameters(hMac.getMacSize());
        } else {
            macParams = pbeGen.generateDerivedMacParameters(hMac.getMacSize() * 8);
        }
        Arrays.fill(passKey, (byte) 0);
        hMac.init(macParams);
        MacInputStream mIn = new MacInputStream(dIn, hMac);
        loadStore(mIn);
        // Finalise our mac calculation
        byte[] mac = new byte[hMac.getMacSize()];
        hMac.doFinal(mac, 0);
        // TODO Should this actually be reading the remainder of the stream?
        // Read the original mac from the stream
        byte[] oldMac = new byte[hMac.getMacSize()];
        dIn.readFully(oldMac);
        if (!Arrays.constantTimeAreEqual(mac, oldMac)) {
            table.clear();
            throw new IOException("KeyStore integrity check failed.");
        }
    } else {
        loadStore(dIn);
        // TODO Should this actually be reading the remainder of the stream?
        // Parse the original mac from the stream too
        byte[] oldMac = new byte[hMac.getMacSize()];
        dIn.readFully(oldMac);
    }
}
Example 30
Project: XobotOS-master  File: JDKKeyStore.java View source code
public void engineLoad(InputStream stream, char[] password) throws IOException {
    table.clear();
    if (// just initialising
    stream == null) {
        return;
    }
    DataInputStream dIn = new DataInputStream(stream);
    int version = dIn.readInt();
    if (version != STORE_VERSION) {
        if (version != 0) {
            throw new IOException("Wrong version of key store.");
        }
    }
    byte[] salt = new byte[dIn.readInt()];
    dIn.readFully(salt);
    int iterationCount = dIn.readInt();
    //
    // we only do an integrity check if the password is provided.
    //
    // BEGIN android-changed
    HMac hMac = new HMac(new OpenSSLDigest.SHA1());
    // END android-changed
    if (password != null && password.length != 0) {
        byte[] passKey = PBEParametersGenerator.PKCS12PasswordToBytes(password);
        // BEGIN android-changed
        PBEParametersGenerator pbeGen = new PKCS12ParametersGenerator(new OpenSSLDigest.SHA1());
        // END android-changed
        pbeGen.init(passKey, salt, iterationCount);
        CipherParameters macParams = pbeGen.generateDerivedMacParameters(hMac.getMacSize());
        Arrays.fill(passKey, (byte) 0);
        hMac.init(macParams);
        MacInputStream mIn = new MacInputStream(dIn, hMac);
        loadStore(mIn);
        // Finalise our mac calculation
        byte[] mac = new byte[hMac.getMacSize()];
        hMac.doFinal(mac, 0);
        // TODO Should this actually be reading the remainder of the stream?
        // Read the original mac from the stream
        byte[] oldMac = new byte[hMac.getMacSize()];
        dIn.readFully(oldMac);
        if (!Arrays.constantTimeAreEqual(mac, oldMac)) {
            table.clear();
            throw new IOException("KeyStore integrity check failed.");
        }
    } else {
        loadStore(dIn);
        // TODO Should this actually be reading the remainder of the stream?
        // Parse the original mac from the stream too
        byte[] oldMac = new byte[hMac.getMacSize()];
        dIn.readFully(oldMac);
    }
}
Example 31
Project: nem.core-master  File: SecP256K1BlockCipher.java View source code
private static IESEngine createIesEngine() {
    return new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()));
}
Example 32
Project: cryptacular-master  File: AbstractOTPGenerator.java View source code
/**
   * Internal OTP generation method.
   *
   * @param  key  Per-user key.
   * @param  count  Counter moving factor.
   *
   * @return  Integer OTP.
   */
protected int generateInternal(final byte[] key, final long count) {
    final HMac hmac = new HMac(getDigest());
    final byte[] output = new byte[hmac.getMacSize()];
    hmac.init(new KeyParameter(key));
    hmac.update(ByteUtil.toBytes(count), 0, 8);
    hmac.doFinal(output, 0);
    return truncate(output) % MODULUS[numberOfDigits];
}
Example 33
Project: TwoFactorBtcWallet-master  File: HDUtils.java View source code
static HMac createHmacSha512Digest(byte[] key) {
    SHA512Digest digest = new SHA512Digest();
    HMac hMac = new HMac(digest);
    hMac.init(new KeyParameter(key));
    return hMac;
}