create_mte_states
- CSharp
- Java
- Python
- Go
/// <summary>
/// Creates the mte states.
/// </summary>
/// <param name="personal">The personal.</param>
/// <param name="entropy">The entropy.</param>
/// <param name="nonce">The nonce.</param>
/// <returns>ResponseModel.</returns>
private static ResponseModel CreateMteStates(string personal,
byte[] encoderEntropy,
byte[] decoderEntropy,
ulong nonce)
{
ResponseModel response = new ResponseModel();
try
{
//--------------------
// Create MTE Encoder
//--------------------
MteEnc encoder = new MteEnc();
encoder.SetEntropy(encoderEntropy);
encoder.SetNonce(nonce);
MteStatus status = encoder.Instantiate(personal);
if (status != MteStatus.mte_status_success)
{
Console.WriteLine($"Error creating encoder: Status: " +
"{encoder.GetStatusName(status)} / {encoder.GetStatusDescription(status)}");
response.Message =
$"Error creating encoder: Status: " +
"{encoder.GetStatusName(status)} / {encoder.GetStatusDescription(status)}";
response.ResultCode = Constants.RC_MTE_ENCODE_EXCEPTION;
response.Success = false;
return response;
}
//------------------------
// Save and encrypt state
//------------------------
var encoderState = encoder.SaveStateB64();
var encryptedEncState = _enc.Encrypt(encoderState, personal, _encIV);
Constants.MteClientState.Store($"{Constants.EncoderPrefix}{personal}",
encryptedEncState,
TimeSpan.FromMinutes(Constants.ExpireMinutes));
//--------------------
// Create MTE Decoder
//--------------------
MteDec decoder = new MteDec();
decoder.SetEntropy(decoderEntropy);
decoder.SetNonce(nonce);
status = decoder.Instantiate(personal);
if (status != MteStatus.mte_status_success)
{
Console.WriteLine($"Error creating decoder: Status: " +
"{decoder.GetStatusName(status)} / {decoder.GetStatusDescription(status)}");
response.Message =
$"Error creating decoder: Status: " +
"{decoder.GetStatusName(status)} / {decoder.GetStatusDescription(status)}";
response.ResultCode = Constants.RC_MTE_DECODE_EXCEPTION;
response.Success = false;
return response;
}
//------------------------
// Save and encrypt state
//------------------------
var decodeState = decoder.SaveStateB64();
var encryptedDecState = _enc.Encrypt(decodeState, personal, _encIV);
Constants.MteClientState.Store($"{Constants.DecoderPrefix}{personal}",
encryptedDecState,
TimeSpan.FromMinutes(Constants.ExpireMinutes));
response.Success = true;
response.ResultCode = Constants.RC_SUCCESS;
response.Message = Constants.STR_SUCCESS;
}
catch (Exception ex)
{
response.Message = $"Exception creating MTE state. Ex: {ex.Message}";
response.ResultCode = Constants.RC_MTE_ENCODE_EXCEPTION;
response.Success = false;
}
return response;
}
/**
* Create Initial MTE states and save to cache
* @param personal --> current conversation id
* @param encoderEntropy --> encoder entropy
* @param decoderEntropy --> decoder entropy
* @param nonce --> MTE nonce
* @return
*/
private static ResponseModel CreateMteStates(String personal,
byte[] encoderEntropy,
byte[] decoderEntropy,
long nonce)
{
ResponseModel response = new ResponseModel();
try
{
//--------------------------
// Create encryption helper
//--------------------------
EncryptionHelper crypt = new EncryptionHelper();
//--------------------
// Create MTE Encoder
//--------------------
MteEnc encoder = new MteEnc();
encoder.setEntropy(encoderEntropy);
encoder.setNonce(nonce);
MteStatus status = encoder.instantiate(personal);
if (status != MteStatus.mte_status_success)
{
System.out.println("Error creating encoder: Status: " +
encoder.getStatusName(status) + " / " +
encoder.getStatusDescription(status));
response.Message =
"Error creating encoder: Status: " +
encoder.getStatusName(status) + " / " +
encoder.getStatusDescription(status);
response.ResultCode = Constants.RC_MTE_ENCODE_EXCEPTION;
response.Success = false;
return response;
}
//------------------------
// Save and encrypt state
//------------------------
String encoderState = encoder.saveStateB64();
String encryptedEncState = crypt.encrypt(encoderState,
EncryptionHelper.SHA256(personal, 64),
_encIV.toString());
_mteStateCacheHelper.Store(Constants.EncoderPrefix + personal, encryptedEncState);
//--------------------
// Create MTE Decoder
//--------------------
MteDec decoder = new MteDec();
decoder.setEntropy(decoderEntropy);
decoder.setNonce(nonce);
status = decoder.instantiate(personal);
if (status != MteStatus.mte_status_success)
{
System.out.println("Error creating decoder: Status: " +
decoder.getStatusName(status) + " / " + decoder.getStatusDescription(status));
response.Message =
"Error creating decoder: Status: " + decoder.getStatusName(status) +
" / " + decoder.getStatusDescription(status);
response.ResultCode = Constants.RC_MTE_DECODE_EXCEPTION;
response.Success = false;
return response;
}
//------------------------
// Save and encrypt state
//------------------------
String decoderState = decoder.saveStateB64();
String encryptedDecState = crypt.encrypt(decoderState,
EncryptionHelper.SHA256(personal, 64),
_encIV.toString());
_mteStateCacheHelper.Store(Constants.DecoderPrefix + personal, encryptedDecState);
response.Success = true;
response.ResultCode = Constants.RC_SUCCESS;
response.Message = Constants.STR_SUCCESS;
}catch(Exception ex) {
response.Message = "Exception creating MTE state. Ex: " + ex.getMessage();
response.ResultCode = Constants.RC_MTE_ENCODE_EXCEPTION;
response.Success = false;
}
return response;
}
def create_mte_states(personal: str, encoder_entropy: str, decoder_entropy: str, nonce: ULONG) -> ResponseModel:
"""
Creates the MTE states.
"""
response = ResponseModel()
# Create the MTE Encoder
encoder = MteEnc.fromdefault()
encoder.set_entropy(base64.b64decode(encoder_entropy))
encoder.set_nonce(nonce)
status = encoder.instantiate(personal)
if status != MteStatus.mte_status_success:
print ("Error creating Encoder: Status: {0} / {1}".format(encoder.get_status_name(status), encoder.get_status_description(status)))
response.message = "Error creating Encoder: Status: {0} / {1}".format(encoder.get_status_name(status), encoder.get_status_description(status))
response.result_code = Constants().RC_MTE_STATE_CREATION
response.success = False
return response
# Save and encrypt state.
encoder_state = encoder.save_state_b64()
encrypted_enc_state = _enc.encrypt(encoder_state, personal, _enc_IV)
_mte_client_state[Constants().ENCODER_PREFIX+personal] = encrypted_enc_state
# Create the MTE Decoder
decoder = MteDec.fromdefault()
decoder.set_entropy(base64.b64decode(decoder_entropy))
decoder.set_nonce(nonce)
status = decoder.instantiate(personal)
if status != MteStatus.mte_status_success:
print ("Error creating Decoder: Status: {0} / {1}".format(decoder.get_status_name(status), decoder.get_status_description(status)))
response.message = "Error creating Decoder: Status: {0} / {1}".format(decoder.get_status_name(status), decoder.get_status_description(status))
response.result_code = Constants().RC_MTE_STATE_CREATION
response.success = False
return response
# Save and encrypt state.
decoder_state = decoder.save_state_b64()
encrypted_dec_state = _enc.encrypt(decoder_state, personal, _enc_IV)
_mte_client_state[Constants().DECODER_PREFIX+personal] = encrypted_dec_state
response.success = True
response.result_code = Constants().RC_SUCCESS
response.message = Constants().STR_SUCCESS
return response
/**
* Creates the MTE Encoder and saves encrypted version to Cache
*/
func CreateMteEncoder(timestamp string, clientId string, encoderEntropy []byte) (out int, err error) {
encoder := mte.NewEncDef()
defer encoder.Destroy()
//----------------------------
// Parse nonce from timestamp
nonce, err := strconv.ParseUint(timestamp, 10, 64)
if err != nil {
fmt.Println(err.Error())
retcode = errorParsingUint
return 0, err
}
//--------------------
// Initialize Encoder
encoder.SetEntropy(encoderEntropy)
encoder.SetNonceInt(nonce)
status := encoder.InstantiateStr(clientId)
if status != mte.Status_mte_status_success {
fmt.Fprintf(os.Stderr, "Encoder instantiate error (%v): %v\n",
mte.GetStatusName(status), mte.GetStatusDescription(status))
return int(status), errors.New("encoder instantiate error ("
+ mte.GetStatusName(status) + "):" + mte.GetStatusDescription(status))
}
//----------------------
// Get the Encoder state
encoderState := encoder.SaveState()
//-----------------------------------------------
// Encrypt the Encoder state
// Creates a new byte array the size of the nonce
aesNonce := make([]byte, gcm.NonceSize())
//-----------------------------------------------------
// Populates our nonce with a cryptographically secure
// Random sequence
if _, err = io.ReadFull(crRand.Reader, aesNonce); err != nil {
fmt.Println(err)
retcode = errorEncryptingState
return 0, err
}
//-----------------------------
// Encrypt/Seal Encoder state
encryptedState := gcm.Seal(aesNonce, aesNonce, encoderState, nil)
//------------------------------
// Set encrypted state to Cache
stateCache.Set([]byte(encPrefix+clientId), encryptedState, cacheExpire)
return 0, nil
}
/**
* Creates the MTE Decoder and saves encrypted version to Cache
*/
func CreateMteDecoder(timestamp string, clientId string, decoderEntropy []byte) (out int, err error) {
decoder := mte.NewDecDef()
defer decoder.Destroy()
//----------------------------
// Parse nonce from timestamp
nonce, err := strconv.ParseUint(timestamp, 10, 64)
if err != nil {
fmt.Println(err.Error())
retcode = errorParsingUint
return 0, err
}
//--------------------
// Initialize Decoder
//--------------------
decoder.SetEntropy(decoderEntropy)
decoder.SetNonceInt(nonce)
status := decoder.InstantiateStr(clientId)
if status != mte.Status_mte_status_success {
fmt.Fprintf(os.Stderr, "Decoder instantiate error (%v): %v\n",
mte.GetStatusName(status), mte.GetStatusDescription(status))
return int(status), errors.New("decoder instantiate error ("
+ mte.GetStatusName(status) + "):" + mte.GetStatusDescription(status))
}
//-------------------------
// Get the Decoder state
decoderState := decoder.SaveState()
//-------------------------------------------------
// Encrypt state before saving in cache
// Creates a new byte array the size of the nonce
aesNonce := make([]byte, gcm.NonceSize())
//------------------------------------------------------
// Populates our nonce with a cryptographically secure
// Random sequence
if _, err = io.ReadFull(crRand.Reader, aesNonce); err != nil {
fmt.Println(err)
retcode = errorEncryptingState
return 0, err
}
//---------------------------------
// Encrypt/Seal the Decoder state
encryptedState := gcm.Seal(aesNonce, aesNonce, decoderState, nil)
//----------------------------------------------
// Set the encrypted Decoder state in the cache
stateCache.Set([]byte(decPrefix+clientId), encryptedState, cacheExpire)
return 0, nil
}