Example usage for org.bouncycastle.crypto.macs HMac update

List of usage examples for org.bouncycastle.crypto.macs HMac update

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.macs HMac update.

Prototype

public void update(byte[] in, int inOff, int len) 

Source Link

Usage

From source file:com.DSC.crypto.Cipher.java

License:Open Source License

/**
 * /*  ww w .j a  va  2 s . co  m*/
 * @param passphrase
 * @param data
 * @return
 */
public static BigInteger[] generateHMAC(String passphrase, byte[] data) {
    HMac hmac = new HMac(new MD5Digest());
    byte[] buf = new byte[hmac.getMacSize()];
    BigInteger[] hmacBigInt = new BigInteger[1];

    /* Initializes and generate HMAC for message */
    hmac.init(new KeyParameter(passphrase.getBytes()));
    hmac.update(data, 0, data.length);
    hmac.doFinal(buf, 0);

    /* Convert the HMAC to a big integer representation */
    hmacBigInt[0] = new BigInteger(buf);
    return hmacBigInt;
}

From source file:com.entertailion.android.shapeways.api.Request.java

License:Apache License

/**
 * Generate HMAC-SHA1 for message/*from   www.  j  ava  2 s  .c om*/
 * 
 * @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", "");
}

From source file:com.google.bitcoin.crypto.HDUtils.java

License:Apache License

static byte[] hmacSha512(HMac hmacSha512, byte[] input) {
    hmacSha512.reset();// ww w. j ava 2s. c om
    hmacSha512.update(input, 0, input.length);
    byte[] out = new byte[64];
    hmacSha512.doFinal(out, 0);
    return out;
}

From source file:com.hanhuy.keepassj.HmacOtp.java

License:Open Source License

public static String Generate(byte[] pbSecret, long uFactor, int uCodeDigits, boolean bAddChecksum,
        int iTruncationOffset) {
    byte[] pbText = MemUtil.UInt64ToBytes(uFactor);
    StrUtil.ArraysReverse(pbText); // Big-Endian

    HMac hsha1 = new HMac(new SHA1Digest());
    KeyParameter key = new KeyParameter(pbSecret);
    hsha1.init(key);/*from ww  w. j  a v  a 2  s  .c o m*/
    byte[] pbHash = new byte[hsha1.getMacSize()];
    hsha1.update(pbText, 0, pbText.length);
    hsha1.doFinal(pbHash, 0);

    int uOffset = (int) (pbHash[pbHash.length - 1] & 0xF);
    if ((iTruncationOffset >= 0) && (iTruncationOffset < (pbHash.length - 4)))
        uOffset = (int) iTruncationOffset;

    int uBinary = (int) (((pbHash[uOffset] & 0x7F) << 24) | ((pbHash[uOffset + 1] & 0xFF) << 16)
            | ((pbHash[uOffset + 2] & 0xFF) << 8) | (pbHash[uOffset + 3] & 0xFF));

    int uOtp = (uBinary % vDigitsPower[uCodeDigits]);
    if (bAddChecksum)
        uOtp = ((uOtp * 10) + CalculateChecksum(uOtp, uCodeDigits));

    int uDigits = (bAddChecksum ? (uCodeDigits + 1) : uCodeDigits);
    return String.format("%0" + uDigits + "d", uOtp);
}

From source file:com.joyent.manta.client.crypto.EncryptingEntityHelper.java

License:Open Source License

/**
 * Creates a new {@link OutputStream} implementation that is backed directly
 * by a {@link CipherOutputStream} or a {@link HmacOutputStream} that wraps
 * a {@link CipherOutputStream} depending on the encryption cipher/mode being
 * used. This allows us to support EtM authentication for ciphers/modes that
 * do not natively support authenticating encryption.
 *
 * NOTE: The design of com.joyent.manta.client.multipart.EncryptionStateRecorder
 * is heavily coupled to this implementation! Changing how these streams are
 * wrapped requires changes to EncryptionStateRecorder!
 *
 * @param httpOut           output stream for writing to the HTTP network socket
 * @param encryptionContext current encryption running state
 * @return a new stream configured based on the parameters
 *//*from   w  w w  . jav  a2  s. com*/
public static OutputStream makeCipherOutputForStream(final OutputStream httpOut,
        final EncryptionContext encryptionContext) {
    final HMac hmac;

    if (encryptionContext.getCipherDetails().isAEADCipher()) {
        hmac = null;
    } else {
        hmac = encryptionContext.getCipherDetails().getAuthenticationHmac();
        Validate.notNull(encryptionContext.getSecretKey(), "Secret key must not be null");
        hmac.init(new KeyParameter(encryptionContext.getSecretKey().getEncoded()));
        /* The first bytes of the HMAC are the IV. This is done in order to
         * prevent IV collision or spoofing attacks. */
        final byte[] iv = encryptionContext.getCipher().getIV();
        hmac.update(iv, 0, iv.length);
    }

    return makeCipherOutputForStream(httpOut, encryptionContext.getCipherDetails(),
            encryptionContext.getCipher(), hmac);
}

From source file:com.joyent.manta.http.EncryptionHttpHelper.java

License:Open Source License

/**
 * Builds a {@link Map} of decrypted metadata keys and values.
 *
 * @param encryptionType encryption type header value
 * @param metadataIvBase64 metadata ciphertext iv header value
 * @param metadataCiphertextBase64 metadata ciphertext header value
 * @param hmacId hmac identifier header value
 * @param metadataHmacBase64 metadata hmac header value
 * @param request http request object//from   w ww  .  ja  v  a  2 s. co  m
 * @param response http response object
 * @return decrypted map of encrypted metadata
 */
@SuppressWarnings("ParameterNumber")
private Map<String, String> buildEncryptedMetadata(final String encryptionType, final String metadataIvBase64,
        final String metadataCiphertextBase64, final String hmacId, final String metadataHmacBase64,
        final HttpRequest request, final HttpResponse response) {
    try {
        EncryptionType.validateEncryptionTypeIsSupported(encryptionType);
    } catch (MantaClientEncryptionException e) {
        HttpHelper.annotateContextedException(e, request, response);
        throw e;
    }

    final byte[] metadataIv = Base64.getDecoder().decode(metadataIvBase64);
    final Cipher metadataCipher = buildMetadataDecryptCipher(metadataIv);

    if (metadataCiphertextBase64 == null) {
        String msg = "No encrypted metadata stored on object";
        MantaClientEncryptionException e = new MantaClientEncryptionException(msg);
        HttpHelper.annotateContextedException(e, request, response);
        throw e;
    }

    final byte[] metadataCipherText = Base64.getDecoder().decode(metadataCiphertextBase64);

    // Validate Hmac if we aren't using AEAD
    if (!cipherDetails.isAEADCipher()) {
        if (hmacId == null) {
            String msg = "No HMAC algorithm specified for metadata ciphertext authentication";
            MantaClientEncryptionException e = new MantaClientEncryptionException(msg);
            HttpHelper.annotateContextedException(e, request, response);
            throw e;
        }

        Supplier<HMac> hmacSupplier = SupportedHmacsLookupMap.INSTANCE.get(hmacId);
        if (hmacSupplier == null) {
            String msg = String.format("Unsupported HMAC specified: %s", hmacId);
            MantaClientEncryptionException e = new MantaClientEncryptionException(msg);
            HttpHelper.annotateContextedException(e, request, response);
            throw e;
        }

        final HMac hmac = hmacSupplier.get();
        initHmac(this.secretKey, hmac);
        hmac.update(metadataCipherText, 0, metadataCipherText.length);

        byte[] actualHmac = new byte[hmac.getMacSize()];
        hmac.doFinal(actualHmac, 0);

        if (metadataHmacBase64 == null) {
            String msg = "No metadata HMAC is available to authenticate metadata ciphertext";
            MantaClientEncryptionException e = new MantaClientEncryptionException(msg);
            HttpHelper.annotateContextedException(e, request, response);
            throw e;
        }

        byte[] expectedHmac = Base64.getDecoder().decode(metadataHmacBase64);

        if (!Arrays.equals(expectedHmac, actualHmac)) {
            String msg = "The expected HMAC value for metadata ciphertext didn't equal the actual value";
            MantaClientEncryptionException e = new MantaClientEncryptionException(msg);
            HttpHelper.annotateContextedException(e, request, null);
            e.setContextValue("expected", Hex.encodeHexString(expectedHmac));
            e.setContextValue("actual", Hex.encodeHexString(actualHmac));
            throw e;
        }
    }

    byte[] plaintext = decryptMetadata(metadataCipherText, metadataCipher);
    return EncryptedMetadataUtils.plaintextMetadataAsMap(plaintext);
}

From source file:com.joyent.manta.http.EncryptionHttpHelper.java

License:Open Source License

/**
 * Attaches encrypted metadata (with e-* values) to the object.
 *
 * @param metadata metadata to append additional values to
 * @throws IOException thrown when there is a problem attaching metadata
 *///from   w ww. ja v  a  2s.c  o  m
public void attachEncryptedMetadata(final MantaMetadata metadata) throws IOException {

    // Create and add encrypted metadata
    Cipher metadataCipher = buildMetadataEncryptCipher();

    metadata.put(MantaHttpHeaders.ENCRYPTION_CIPHER, cipherDetails.getCipherId());

    String metadataIvBase64 = Base64.getEncoder().encodeToString(metadataCipher.getIV());
    metadata.put(MantaHttpHeaders.ENCRYPTION_METADATA_IV, metadataIvBase64);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Encrypted metadata IV: {}", Hex.encodeHexString(metadataCipher.getIV()));
    }

    String metadataPlainTextString = EncryptedMetadataUtils.encryptedMetadataAsString(metadata);
    LOGGER.debug("Encrypted metadata plaintext:\n{}", metadataPlainTextString);
    LOGGER.debug("Encrypted metadata ciphertext: {}", metadataIvBase64);

    byte[] metadataCipherText = encryptMetadata(metadataPlainTextString, metadataCipher);
    String metadataCipherTextBase64 = Base64.getEncoder().encodeToString(metadataCipherText);

    if (metadataCipherTextBase64.length() > MAX_METADATA_CIPHERTEXT_BASE64_SIZE) {
        String msg = "Encrypted metadata exceeded the maximum size allowed";
        MantaClientEncryptionException e = new MantaClientEncryptionException(msg);
        e.setContextValue("max_size", MAX_METADATA_CIPHERTEXT_BASE64_SIZE);
        e.setContextValue("actual_size", metadataCipherTextBase64.length());
        throw e;
    }

    metadata.put(MantaHttpHeaders.ENCRYPTION_METADATA, metadataCipherTextBase64);

    if (!this.cipherDetails.isAEADCipher()) {
        final HMac hmac = this.cipherDetails.getAuthenticationHmac();
        initHmac(this.secretKey, hmac);

        hmac.update(metadataCipherText, 0, metadataCipherText.length);

        byte[] checksum = new byte[hmac.getMacSize()];
        hmac.doFinal(checksum, 0);

        String checksumBase64 = Base64.getEncoder().encodeToString(checksum);
        metadata.put(MantaHttpHeaders.ENCRYPTION_METADATA_HMAC, checksumBase64);

        LOGGER.debug("Encrypted metadata HMAC: {}", checksumBase64);
    } else {
        metadata.put(MantaHttpHeaders.ENCRYPTION_METADATA_AEAD_TAG_LENGTH,
                String.valueOf(this.cipherDetails.getAuthenticationTagOrHmacLengthInBytes()));
    }
}

From source file:com.joyent.manta.serialization.EncryptedMultipartUploaSerializationHelper.java

License:Open Source License

/**
 * Serializes and encrypts the specified upload object.
 *
 * @param upload object to serialize and encrypt
 * @return serialized and encrypted byte array
 *///from  w  w w .  j  av a 2  s.com
public byte[] serialize(final EncryptedMultipartUpload<WRAPPED> upload) {
    Cipher cipher = cipherDetails.getCipher();
    byte[] iv = cipherDetails.generateIv();

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Writing IV: {}", Hex.toHexString(iv));
    }

    try {
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, cipherDetails.getEncryptionParameterSpec(iv));
    } catch (GeneralSecurityException e) {
        String msg = String.format("Unable to initialize cipher [%s]", cipherDetails.getCipherId());
        throw new MantaClientEncryptionException(msg, e);
    }

    final byte[] serializedData;
    // 16k buffer *should* handle the serialized content
    final int outputBufferSize = 8192;
    final int maxBufferSize = 16384;
    try (Output output = new ByteBufferOutput(outputBufferSize, maxBufferSize)) {
        output.writeVarInt(ENCRYPTED_MULTIPART_UPLOAD_SERIALIZATION_VERSION, true);
        kryo.writeClassAndObject(output, upload);
        output.flush();
        serializedData = output.toBytes();
    }

    final byte[] cipherText;

    try {
        cipherText = cipher.doFinal(serializedData);
    } catch (GeneralSecurityException e) {
        String msg = "Error encrypting serialized data";
        throw new MantaClientEncryptionException(msg, e);
    }

    // Authentication HMAC
    if (!cipherDetails.isAEADCipher()) {
        HMac hmac = cipherDetails.getAuthenticationHmac();
        hmac.update(iv, 0, iv.length);
        hmac.update(cipherText, 0, cipherText.length);
        final byte[] checksum = new byte[hmac.getMacSize()];
        hmac.doFinal(checksum, 0);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Writing HMAC: {}", Hex.toHexString(checksum));
        }

        final byte[] hmacId = new byte[CIPHER_ID_SIZE_BYTES];
        final String hmacIdString = SupportedHmacsLookupMap.hmacNameFromInstance(hmac);
        final byte[] hmacIdStringBytes = hmacIdString.getBytes(StandardCharsets.US_ASCII);
        System.arraycopy(hmacIdStringBytes, 0, hmacId, 0, hmacIdStringBytes.length);

        return addAll(iv, cipherText, checksum, hmacId);
    }

    return addAll(iv, cipherText);
}

From source file:com.joyent.manta.serialization.EncryptedMultipartUploaSerializationHelper.java

License:Open Source License

/**
 * Decrypts and deserializes the specified binary blob.
 *
 * @param serializedData data to decrypt and deserialize
 * @return an upload object//from w  w w. j  a v  a  2s  .c  o  m
 */
@SuppressWarnings("unchecked")
public EncryptedMultipartUpload<WRAPPED> deserialize(final byte[] serializedData) {
    final byte[] iv = Arrays.copyOf(serializedData, cipherDetails.getIVLengthInBytes());

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Reading IV: {}", Hex.toHexString(iv));
    }

    final Cipher cipher = cipherDetails.getCipher();
    try {
        cipher.init(Cipher.DECRYPT_MODE, secretKey, cipherDetails.getEncryptionParameterSpec(iv));
    } catch (GeneralSecurityException e) {
        String msg = String.format("Unable to initialize cipher [%s]", cipherDetails.getCipherId());
        throw new MantaClientEncryptionException(msg, e);
    }

    final byte[] cipherText;

    if (cipherDetails.isAEADCipher()) {
        cipherText = extractCipherText(serializedData, iv.length, null);
    } else {
        final byte[] hmacIdBytes = Arrays.copyOfRange(serializedData,
                serializedData.length - CIPHER_ID_SIZE_BYTES, serializedData.length);
        final String hmacId = new String(hmacIdBytes, StandardCharsets.US_ASCII).trim();

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Verifying checksum with [{}]", hmacId);
        }

        final Supplier<HMac> hmacSupplier = SupportedHmacsLookupMap.INSTANCE.get(hmacId);

        if (hmacSupplier == null) {
            String msg = String.format("Unknown HMAC: [%s]", hmacId);
            throw new MantaClientEncryptionException(msg);
        }

        final HMac hmac = hmacSupplier.get();
        final int hmacLength = hmac.getMacSize();

        cipherText = extractCipherText(serializedData, iv.length, hmacLength);

        hmac.update(iv, 0, iv.length);
        hmac.update(cipherText, 0, cipherText.length);
        final byte[] calculated = new byte[hmacLength];
        hmac.doFinal(calculated, 0);

        final byte[] expected = Arrays.copyOfRange(serializedData,
                serializedData.length - hmacLength - CIPHER_ID_SIZE_BYTES,
                serializedData.length - CIPHER_ID_SIZE_BYTES);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Expected HMAC:   {}", Hex.toHexString(expected));
            LOGGER.debug("Calculated HMAC: {}", Hex.toHexString(calculated));
        }

        if (!Arrays.areEqual(calculated, expected)) {
            String msg = "Serialization data ciphertext failed " + "cryptographic authentication";
            MantaClientEncryptionCiphertextAuthenticationException e = new MantaClientEncryptionCiphertextAuthenticationException(
                    msg);
            e.setContextValue("expected", Hex.toHexString(expected));
            e.setContextValue("calculated", Hex.toHexString(calculated));
            throw e;
        }
    }

    final byte[] plaintext;
    try {
        plaintext = cipher.doFinal(cipherText);
    } catch (GeneralSecurityException e) {
        String msg = "Error decrypting serialized object data";
        throw new MantaClientEncryptionException(msg, e);
    }

    final EncryptedMultipartUpload<WRAPPED> upload;

    try (Input input = new Input(plaintext)) {
        final int serializationVersion = input.readVarInt(true);

        if (serializationVersion != ENCRYPTED_MULTIPART_UPLOAD_SERIALIZATION_VERSION) {
            LOGGER.warn("Deserialized version [%d] is different than serialization version [%d",
                    serializationVersion, ENCRYPTED_MULTIPART_UPLOAD_SERIALIZATION_VERSION);
        }

        upload = (EncryptedMultipartUpload<WRAPPED>) kryo.readClassAndObject(input);
    }

    return upload;
}

From source file:com.joyent.manta.serialization.HmacSerializerTest.java

License:Open Source License

private void canSerializeHmac(final String algorithm) throws Exception {
    final byte[] dataIn1 = new byte[] { (byte) 4, (byte) 83, (byte) 113, (byte) 66 };
    final byte[] dataIn2 = new byte[] { (byte) 4, (byte) 83, (byte) 113, (byte) 66 };
    final byte[] expected;
    final byte[] actual;

    {/*  ww  w  .j  a v  a 2 s .  c  o m*/
        HMac hmacExpected = SupportedHmacsLookupMap.INSTANCE.get(algorithm).get();
        hmacExpected.init(new KeyParameter(this.secretKey.getEncoded()));
        hmacExpected.update(dataIn1, 0, dataIn1.length);
        hmacExpected.update(dataIn1, 0, dataIn2.length);
        expected = new byte[hmacExpected.getMacSize()];
        actual = new byte[hmacExpected.getMacSize()];
        hmacExpected.doFinal(expected, 0);
    }

    HMac hmac = SupportedHmacsLookupMap.INSTANCE.get(algorithm).get();
    hmac.init(new KeyParameter(this.secretKey.getEncoded()));
    hmac.update(dataIn1, 0, dataIn1.length);

    final byte[] serializedContent;

    try (ByteArrayOutputStream out = new ByteArrayOutputStream(); Output output = new Output(out)) {
        kryo.writeObject(output, hmac);
        output.flush();

        serializedContent = out.toByteArray();
    }

    try (Input input = new FastInput(serializedContent)) {
        HMac deserialized = kryo.readObject(input, HMac.class);

        deserialized.update(dataIn2, 0, dataIn2.length);
        deserialized.doFinal(actual, 0);

        AssertJUnit.assertArrayEquals("Deserialized hmac couldn't compute equivalent value", expected, actual);
    }
}