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

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

Introduction

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

Prototype

public int doFinal(byte[] out, int outOff) 

Source Link

Usage

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

License:Open Source License

/**
 * // ww w . j  a v  a  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/* w w w.  ja va  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();/*w w w .ja v  a2 s  .  com*/
    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 w  w  w  .j a va2s .  c om
    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.EncryptingEntity.java

License:Open Source License

@Override
public void writeTo(final OutputStream httpOut) throws IOException {
    /*/* w w w.  j  a  v a 2  s.co m*/
     * Construct a fresh EncryptionContext each time we attempt to write out the entity.
     * Calling encryptionContext.initializeCipher(getCipher().getIV()) from here would be ideal
     * but is not compatible with AES-GCM
     */
    this.encryptionContext = new EncryptionContext(encryptionContext.getSecretKey(),
            encryptionContext.getCipherDetails(), encryptionContext.getCipher().getIV());

    OutputStream out = EncryptingEntityHelper.makeCipherOutputForStream(httpOut, encryptionContext);

    copyContentToOutputStream(out);
    /* We don't close quietly because we want the operation to fail if
     * there is an error closing out the CipherOutputStream. */
    out.close();

    if (out instanceof HmacOutputStream) {
        final HMac hmac = ((HmacOutputStream) out).getHmac();
        final int hmacSize = hmac.getMacSize();
        final byte[] hmacBytes = new byte[hmacSize];
        hmac.doFinal(hmacBytes, 0);

        Validate.isTrue(hmacBytes.length == hmacSize,
                "HMAC actual bytes doesn't equal the number of bytes expected");

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("HMAC: {}", Hex.encodeHexString(hmacBytes));
        }

        httpOut.write(hmacBytes);
    }
}

From source file:com.joyent.manta.client.multipart.EncryptionState.java

License:Open Source License

ByteArrayOutputStream remainderAndLastPartAuth() throws IOException {
    if (!getLock().isHeldByCurrentThread()) {
        throw new IllegalStateException("remainderAndLastPartAuth called without lock owned");
    }//w w w .j a  v a  2s. com
    if (isLastPartAuthWritten()) {
        final String msg = "final CSE auth already written (complete called multiple times or "
                + "parts below min size)";
        MantaMultipartException mme = new MantaMultipartException(new IllegalStateException(msg));
        mme.setContextValue("lastPartNumber", getLastPartNumber());
        throw mme;
    }
    ByteArrayOutputStream remainderStream = new ByteArrayOutputStream();
    getMultipartStream().setNext(remainderStream);
    getCipherStream().close();
    remainderStream.write(getMultipartStream().getRemainder());

    if (getCipherStream().getClass().equals(HmacOutputStream.class)) {
        HMac hmac = ((HmacOutputStream) getCipherStream()).getHmac();
        byte[] hmacBytes = new byte[hmac.getMacSize()];
        hmac.doFinal(hmacBytes, 0);

        final int hmacSize = encryptionContext.getCipherDetails().getAuthenticationTagOrHmacLengthInBytes();

        Validate.isTrue(hmacBytes.length == hmacSize,
                "HMAC actual bytes doesn't equal the number of bytes expected");

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("HMAC: {}", Hex.encodeHexString(hmacBytes));
        }
        remainderStream.write(hmacBytes);
    }
    lastPartAuthWritten = true;
    return remainderStream;
}

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  .j  a v a2  s  .c  o  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
 *//* w  w w  . j a 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 ww  w  . ja  va 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//ww w .  j a v  a  2 s  . c om
 */
@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;
}