All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.akeyless.crypto.utils.Utils Maven / Gradle / Ivy

There is a newer version: 0.0.10
Show newest version
package com.akeyless.crypto.utils;


import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

public final class Utils {

    private static final int AKEYLESS_VERSION = 1;

    private static final int AKEYLESS_VERSION_BYTES_LEN = 1;
    private static final int KEY_VERSION_BYTES_LEN = 4;
    private static final int DERIVATION_DATA_LEN = 8;
    private static final int DD_LEN_ST_INDEX = AKEYLESS_VERSION_BYTES_LEN + KEY_VERSION_BYTES_LEN;
    private static final int DD_LEN_EN_INDEX = DD_LEN_ST_INDEX + 1;
    private static final int NUM_OF_DD_ST_INDEX = DD_LEN_EN_INDEX;
    private static final int NUM_OF_DD_EN_INDEX = NUM_OF_DD_ST_INDEX + 1;
    private static final int HEADER_DD_LEN = 2;

    public static byte[] genDerivationData() {
        byte[] dd = new byte[DERIVATION_DATA_LEN];
        SecureRandomGen.get().nextBytes(dd);
        return dd;
    }

    public static byte[] combineEncryptedDataAndHeaders(Integer keyVersion, byte[] combinedDD, byte[] encryptedData) {
        ByteBuffer bb = ByteBuffer.allocate(AKEYLESS_VERSION_BYTES_LEN + KEY_VERSION_BYTES_LEN +
                combinedDD.length+encryptedData.length);
        bb.put((byte) AKEYLESS_VERSION_BYTES_LEN);
        bb.put(ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(keyVersion).array());
        bb.put(combinedDD);
        bb.put(encryptedData);
        return bb.array();
    }

    public static byte[] combineDDForNondeterministicAlg(byte[] derivationData) {
        byte numOfDD = 1;
        ByteBuffer bb = ByteBuffer.allocate(HEADER_DD_LEN+derivationData.length);
        bb.put((byte) derivationData.length);
        bb.put(numOfDD);
        bb.put(derivationData);
        return bb.array();
    }

    public static byte[] extractDerivationsDataFromCipher(byte[] cipher) {
        int derivationDataLen = Arrays.copyOfRange(cipher, DD_LEN_ST_INDEX, DD_LEN_EN_INDEX)[0];
        return Arrays.copyOfRange(cipher, NUM_OF_DD_EN_INDEX, NUM_OF_DD_EN_INDEX + derivationDataLen);
    }

    public static byte[] extractEncryptedDataFromCipher(byte[] cipher) {
        int derivationDataLen = Arrays.copyOfRange(cipher, DD_LEN_ST_INDEX, DD_LEN_EN_INDEX)[0];
        return Arrays.copyOfRange(cipher, NUM_OF_DD_EN_INDEX+derivationDataLen, cipher.length);
    }

    public static Integer extractKeyVersionFromCipher(byte[] cipher) {
        byte[] keyVersionBytes = Arrays.copyOfRange(cipher, AKEYLESS_VERSION_BYTES_LEN,
                AKEYLESS_VERSION_BYTES_LEN+KEY_VERSION_BYTES_LEN);
        ByteBuffer buf = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).put(keyVersionBytes);
        buf.flip();
        return buf.getInt();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy