#include "Ap4KeyWrap.h"
#include "Ap4AesBlockCipher.h"
#include "Ap4Utils.h"
AP4_Result
AP4_AesKeyWrap(const AP4_UI08* kek,
const AP4_UI08* cleartext_key,
AP4_Size cleartext_key_size,
AP4_DataBuffer& wrapped_key)
{
if (cleartext_key_size % 8) {
return AP4_ERROR_INVALID_PARAMETERS;
}
unsigned int n = cleartext_key_size/8;
wrapped_key.SetDataSize((n+1)*8);
AP4_UI08* a = (AP4_UI08*)wrapped_key.UseData();
AP4_SetMemory(a, 0xA6, 8);
AP4_UI08* r = a+8;
AP4_CopyMemory(r, cleartext_key, cleartext_key_size);
AP4_AesBlockCipher* block_cipher = NULL;
AP4_Result result = AP4_AesBlockCipher::Create(kek,
AP4_BlockCipher::ENCRYPT,
AP4_BlockCipher::CBC,
NULL,
block_cipher);
if (AP4_FAILED(result)) return result;
for (unsigned int j=0; j <= 5; j++) {
r = a + 8;
for (unsigned int i=1; i<=n; i++) {
AP4_UI08 workspace[16];
AP4_UI08 b[16];
AP4_CopyMemory(workspace, a, 8);
AP4_CopyMemory(&workspace[8], r, 8);
block_cipher->Process(workspace, 16, b, NULL);
AP4_CopyMemory(a, b, 8);
a[7] ^= n*j+i;
AP4_CopyMemory(r, &b[8], 8);
r += 8;
}
}
delete block_cipher;
return AP4_SUCCESS;
}
AP4_Result
AP4_AesKeyUnwrap(const AP4_UI08* kek,
const AP4_UI08* wrapped_key,
AP4_Size wrapped_key_size,
AP4_DataBuffer& cleartext_key)
{
if ((wrapped_key_size % 8) || (wrapped_key_size < 24)) {
return AP4_ERROR_INVALID_PARAMETERS;
}
unsigned int n = (wrapped_key_size/8)-1;
cleartext_key.SetDataSize(n*8);
AP4_UI08 a[8];
AP4_CopyMemory(a, wrapped_key, 8);
AP4_UI08* r = (AP4_UI08*)cleartext_key.UseData();
AP4_CopyMemory(r, wrapped_key+8, 8*n);
AP4_AesBlockCipher* block_cipher = NULL;
AP4_Result result = AP4_AesBlockCipher::Create(kek,
AP4_BlockCipher::DECRYPT,
AP4_BlockCipher::CBC,
NULL,
block_cipher);
if (AP4_FAILED(result)) return result;
for (int j=5; j>=0; j--) {
r = (AP4_UI08*)cleartext_key.UseData()+(n-1)*8;
for (int i=n; i>=1; i--) {
AP4_UI08 workspace[16];
AP4_UI08 b[16];
AP4_CopyMemory(workspace, a, 8);
workspace[7] ^= (n*j)+i;
AP4_CopyMemory(&workspace[8], r, 8);
block_cipher->Process(workspace, 16, b, NULL);
AP4_CopyMemory(a, b, 8);
AP4_CopyMemory(r, &b[8], 8);
r -= 8;
}
}
delete block_cipher;
for (unsigned int i=0; i<8; i++) {
if (a[i] != 0xA6) {
cleartext_key.SetDataSize(0);
return AP4_ERROR_INVALID_FORMAT;
}
}
return AP4_SUCCESS;
}