Derive 4 specific size integers from a string - math

I need to generate 4: 6, 7, 44, and 8 bit integers for a cipher project I'm working on.
How would I go on about doing this in lua as a cryptographically secure function?
What I've tried:
-- derive secret from the whole string
-- 6-bit integer = byte % 64
-- 7-bit integer = byte % 128
-- 44-bit integer = byte % 17592186044416
-- 8-bit integer = byte % 256
local secret = { 2, 2, 2, 2 }
for i = 1, #str do
local _byte = byte(str, i)
secret[1] = (secret[1] * _byte + 1) % 64
secret[2] = (secret[2] * _byte + 1) % 128
secret[3] = (secret[3] * _byte + 1) % 17592186044416
secret[4] = (secret[4] * _byte + 1) % 256
end
return secret
I am pretty sure what I have isn't cryptographically secure nor reliable
This is what my random secret function does, it generates usable integers, but it doesn't derive them from a string:
local secret = {
random:NextNumber(0, 63), --// 6-bit arbitrary integer (0..63)
random:NextNumber(0, 127), --// 7-bit arbitrary integer (0..127)
random:NextNumber(0, 17592186044415), --// 44-bit arbitrary integer (0..17592186044415)
random:NextNumber(0, 255); --// 8-bit arbitrary integer (0..255)
};

Related

What is missing from the AES Validation Standard Pseudocode for the Monte Carlo Tests?

I'm trying to use the prescribed validation procedure for AES-128 in CBC mode, as defined in the NIST AESAVS standard. One of the more important parts of the test suite is the Monte Carlo test, which provides an algorithm for generating many 10000 pseudorandom tests cases such that it is unlikely that a hardcoded circuit could fake AES. The algorithm pseudocode therein appears to be taking some liberties with variable scope and definition, so I am hoping someone could help me fill in the missing information to interpret this correctly.
The verbatim algorithm for the 128-bit key case is as follows:
Key[0] = Key
IV[0] = IV
PT[0] = PT
For i = 0 to 99
Output Key[i]
Output IV[i]
Output PT[0]
For j = 0 to 999
If ( j=0 )
CT[j] = AES(Key[i], IV[i], PT[j])
PT[j+1] = IV[i]
Else
CT[j] = AES(Key[i], PT[j])
PT[j+1] = CT[j-1]
Output CT[j]
Key[i+1] = Key[i] xor CT[j]
IV[i+1] = CT[j]
PT[0] = CT[j-1]
For the above pseudocode, starting with these initial values:
Key = 9dc2c84a37850c11699818605f47958c
IV = 256953b2feab2a04ae0180d8335bbed6
PT = 2e586692e647f5028ec6fa47a55a2aab
The first three iterations of the outer loop should output:
KEY = 9dc2c84a37850c11699818605f47958c
IV = 256953b2feab2a04ae0180d8335bbed6
PLAINTEXT = 2e586692e647f5028ec6fa47a55a2aab
CIPHERTEXT = 1b1ebd1fc45ec43037fd4844241a437f
KEY = 86dc7555f3dbc8215e6550247b5dd6f3
IV = 1b1ebd1fc45ec43037fd4844241a437f
PLAINTEXT = c1b77ed52521525f0a4ba341bdaf51d9
CIPHERTEXT = bf43583a665fa45fdee831243a16ea8f
KEY = 399f2d6f95846c7e808d6100414b3c7c
IV = bf43583a665fa45fdee831243a16ea8f
PLAINTEXT = 7cbeea19157ec7bbf6289e2dff5e8ee4
CIPHERTEXT = 5464e1900f81e06f67139456da25fc09
It looks like we are using j outside of the inner loop, which I believe is the source of the confusion. I had originally assumed that this meant whatever the final value of the ciphertext CT was (CT[999]), which would lead me to believe that the plaintext for the next outer loop PT[0] is initialized to CT[998]. However, this interpretation doesn't match the expected outputs given.
I also thought that maybe brackets are not indicating an array of values here, but rather they represent the time steps relative to now. However, this also makes referencing j outside of the loop confusing. If the loop has expired, then is i or j the current time?
Am I missing some crucial step here? Is there a typo (there is no errata in the document)?
Could anyone with some experience on the matter comment on the appropriate interpretation?
Some months ago I tried to get the AES CBC MonteCarlo running on Java. I encountered the same problems but in the end I could find a complete and running solution that meets the official NIST vector results.
Before I start - your inital test vector seems to be an own vector but not the one provided by NIST - here is the link to the official NIST-website with all AES testvectors:
NIST-Website: https://csrc.nist.gov/Projects/cryptographic-algorithm-validation-program/Block-Ciphers Montecarlo testvectors: https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/aes/aesmct.zip
My test will start with these data:
[ENCRYPT]
COUNT = 0
KEY = 8809e7dd3a959ee5d8dbb13f501f2274
IV = e5c0bb535d7d54572ad06d170a0e58ae
PLAINTEXT = 1fd4ee65603e6130cfc2a82ab3d56c24
CIPHERTEXT = b127a5b4c4692d87483db0c3b0d11e64
and the function uses a "double" byte array for the inner and outer loop. I do not present the complete sourcode here on SO but the complete code is available in my GitHub repository https://github.com/java-crypto/Known_Answer_Tests with many other tests and test vector files. The encryption/decryption has to be done with NoPadding - don't use AES in default mode as in most
cases it would run with PKCS#5/#7 padding.
If you like you can run the code online (reduced to AES CBC 128 MonteCarlo) here: https://repl.it/#javacrypto/AesCbcMonteCarloTest#Main.java
The program will run the complete encryption and decryption test and does an additional cross-check (means the encryption result is checked
by a decryption and vice versa).
As it is some months ago that I took care of this I'm just offering my solution in Java code - hopefully it helps you in
your understanding of the NIST test procedure.
public static byte[] aes_cbc_mct_encrypt(byte[] PLAINTEXT, byte[] KEYinit, byte[] IVinit) throws Exception {
int i = 0; // outer loop
int j = 0; // inner loop
byte[][] KEY = new byte[101][128];
byte[][] IV = new byte[1001][128];
byte[][] PT = new byte[1001][128]; // plaintext
byte[][] CT = new byte[1001][128]; // ciphertext
byte[] CTsave = new byte[256]; // nimmt den letzten ct fuer nutzung als neuen iv auf
// init
int KEYLENGTH = KEYinit.length * 8;
KEY[0] = KEYinit;
IV[0] = IVinit;
PT[0] = PLAINTEXT;
for (i = 0; i < 100; i++) {
for (j = 0; j < 1000; j++) {
if (j == 0) {
CT[j] = aes_cbc_encrypt(PT[j], KEY[i], IV[i]);
CTsave = CT[j]; // sicherung fuer naechsten iv
PT[j + 1] = IV[i];
} else {
IV[i] = CTsave;
CT[j] = aes_cbc_encrypt(PT[j], KEY[i], IV[i]);
CTsave = CT[j];
PT[j + 1] = CT[j - 1];
}
}
j = j - 1; // correction of loop counter
if (KEYLENGTH == 128) {
KEY[i + 1] = xor(KEY[i], CT[j]);
}
if (KEYLENGTH == 192) {
KEY[i + 1] = xor192(KEY[i], CT[j - 1], CT[j]);
}
if (KEYLENGTH == 256) {
KEY[i + 1] = xor256(KEY[i], CT[j - 1], CT[j]);
}
IV[i + 1] = CT[j];
PT[0] = CT[j - 1];
ctCalculated[i] = CT[j].clone();
}
return CT[j];
}
public static byte[] xor(byte[] a, byte[] b) {
// nutzung in der mctCbcEncrypt und mctCbcDecrypt methode
byte[] result = new byte[Math.min(a.length, b.length)];
for (int i = 0; i < result.length; i++) {
result[i] = (byte) (((int) a[i]) ^ ((int) b[i]));
}
return result;
}
public static byte[] aes_cbc_encrypt(byte[] plaintextByte, byte[] keyByte, byte[] initvectorByte) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, BadPaddingException, IllegalBlockSizeException {
byte[] ciphertextByte = null;
SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
IvParameterSpec ivKeySpec = new IvParameterSpec(initvectorByte);
Cipher aesCipherEnc = Cipher.getInstance("AES/CBC/NOPADDING");
aesCipherEnc.init(Cipher.ENCRYPT_MODE, keySpec, ivKeySpec);
ciphertextByte = aesCipherEnc.doFinal(plaintextByte);
return ciphertextByte;
}

OpenCL kernel math outputs incorrect results

I am currently trying to implement an OpenCL kernel. The kernel is supposed to output a number of previously calculated elements divided by the total number of elements remapped to a value from 0 to 255.
The kernel runs in a single work group with 256 work items where LX is the local ID:
#define LX get_local_id(0)
kernel void reduceStatistic(global int *inout, int nr_workgroups, int nr_pixels)
{
int i = 1;
for (; i < nr_workgroups; i++)
{
inout[LX] += inout[LX + i * 256];
}
inout[LX] = (int)floor(((float)inout[LX] / (float)nr_pixels) * 256.0f);
}
The calculation before the remapping operation is for clean up after a previous calculation on the same buffer.
The first item of inout[LX] after the cleanup is 17176, the nr_pixels is 160000 so this should result in a value of 27 using the calculation above. The code, however, returns 6.
The relevant host-side code is as follows:
// nr_workgroups is of type int
cl_mem outputBuffer = clCreateBuffer(mgr->context, CL_MEM_READ_WRITE, nr_workgroups * 256 * sizeof(cl_int), NULL, NULL);
// another kernel writes into outputBuffer
// set kernel arguments
clSetKernelArg(mgr->reduceStatisticKernel, 0, sizeof(outputBuffer), &outputBuffer);
clSetKernelArg(mgr->reduceStatisticKernel, 1, sizeof(cl_int), &nr_workgroups);
clSetKernelArg(mgr->reduceStatisticKernel, 2, sizeof(cl_int), &imgSeqSize);
size_t global_work_size_statistics[1] = { 256 };
size_t local_work_size_statistics[1] = { 256 };
// run the kernel
clEnqueueNDRangeKernel(mgr->commandQueue, mgr->reduceStatisticKernel, 1, NULL, global_work_size_statistics, local_work_size_statistics, 0, NULL, NULL);
// read result
cl_int *reducedResult = new cl_int[256];
clEnqueueReadBuffer(mgr->commandQueue, outputBuffer, CL_TRUE, 0, 256 * sizeof(cl_int), reducedResult, 0, NULL, NULL);
Help much appreciated! (:
We established in the comments that the global buffer index calculation is wrong:
inout[LX] += inout[LX + i * 265];
----------^^^
Should be 256
Going out of range on a buffer leads to undefined behaviour, so this is always one of the prime culprits to look for.

Converting 16 bit integer into 0..100

I have a system that takes/gives volume (as in an audio amplifier) as a 16-bit unsigned integer. I have another system that takes/gives volume as a integer between 0 and 100.
0 is 0
100 is 65535
What's the math to convert to/from? E.g. in C#.
Dividing by 655.36 is the same thing as multiplying by 100 and then dividing by 65536, which can be done purely in integer arithmetic:
int scaled = input * 100 >> 16;
That's biased downwards however (and therefore does not ever result in 100), because of the truncation implicit in the division/right shift. You can make it round evenly by adding a bias of 0.5,
int temp = input * 100;
temp += 0x8000; // 0x8000 = 0.5 in Q16
int scaled = temp >> 16;
Here, 0xfeb9 and up will result in 100. If that wasn't supposed to happen because 100 was an exclusive bound, you can of course multiply by 99 instead.
The other way around can be done using the same principles,
int scaled = ((input << 16) - 50) / 100;
This ensures that 100 -> 65535, 65536 is not a 16 bit number so it should probably be avoided.
A largely similar thing can be done shorter but with extra multiplication,
int scaled = input * 65535 / 100;
Which distributes the results a bit differently but it doesn't make a lot of difference.
Using Vala, which is very similar to C# (a very rough and simple approach):
public static int convert_from_unsigned_int_to_percentage (uint16 val) {
return (int) ((val / 65535.0) * 100);
}
public static uint16 convert_from_percentage_to_unsigned_int (int val) {
return (uint16) ((val / 100.0) * 65535);
}
int main (string[] args) {
print ("test1 65535 -> ? = %d\n", convert_from_unsigned_int_to_percentage (65535));
print ("test1 32500 -> ? = %d\n", convert_from_unsigned_int_to_percentage (32500));
print ("test1 100%% -> ? = %d\n", convert_from_percentage_to_unsigned_int (100));
print ("test1 50%% -> ? = %d\n", convert_from_percentage_to_unsigned_int (50));
return 0;
}
Output:
./volume
test1 65535 -> ? = 100
test1 32500 -> ? = 49
test1 100% -> ? = 65535
test1 50% -> ? = 32767

How to decrypt a message using the Vigenere Cipher

Recently, I have been trying to educate myself on how to encrypt and decrypt using the Vigenere Cipher.
I have successfully encrypted the message and these are the steps I undertook to achieve encryption:
Encryption Key: Set
Message: Top secret
Step 1: Numerical representation of key is 18, 4, 19 (Using the table below)
Working Out:
Reminder:
P is the set of plaintext units
C is the set of ciphertext units
K is the set of keys
E: P x K -> C is the encryption function
D: C x K -> P is the decryption function
Plaintext: top secret
Ciphertext: ISIKIVJIM
Although I have managed to encrypt the message "top secret" I am struggling to decrypt messages using the Vigenere Cipher method using the numerical technique I used above. Can someone explain to me how I can decrypt lets say: ISIKIVJIM (the ciphertext from above) to its original plain text message which is "top secret".
Thanks.
As pointed out in the comments the decryption formula is : p = c - k mod 26, also note that we have to perform modular arithmetic so our answer for any input should belong in the range of 0 - 25, i.e if we get a negative number we can add 26(i.e the number we are taking modulo by) until we are within this range you can read more about this here :
https://en.wikipedia.org/wiki/Modular_arithmetic
So the decryption will be like :
L = 11 - 18 = -7 mod 26 = -7 + 26 = 19 = T
S = 18 - 4 = 14 mod 26 = 14 = O
I = 8 - 19 = -11 mod 26 = -11 + 26 = 15 = P
ans so on...
I have also written a c++ code : http://ideone.com/M3BAmq
I recently wrote a java program that encrypts and decrypts in Vigenere using bytes. You need to convert the plain text/ crypt text into byte array and pass it in.
public static byte [] encryptVigenere (byte [] pt, String key)
{
byte [] c_text = new byte [pt.length];
byte [] key_text = key.getBytes();
byte tmp;
int shift;
for (int i = 0, j = 0; i < pt.length; i++)
{
if (j >= key_text.length)
j = 0;
shift = key_text[j] - 65; //index of alphabet
tmp = (byte) (pt[i] + shift);
if (tmp > 'Z')
tmp = (byte) (pt[i] - (26-shift));
c_text[i] = tmp;
j++;
}
return c_text;
}
public static byte [] decryptVigenere (byte [] ct, String key)
{
byte [] p_text = new byte [ct.length];
byte [] key_text = key.getBytes();
byte tmp;
int shift;
for (int i = 0, j = 0; i < ct.length; i++)
{
if (j >= key_text.length)
j = 0;
shift = key_text[j] - 65; //index of alphabet
tmp = (byte) (ct[i] - shift);
if (tmp < 'A')
tmp = (byte) (ct[i] + (26-shift));
p_text[i] = tmp;
j++;
}
return p_text;
}

Cipher Feedback mode c++ implementation

HI I am tiring to implement a CFB with DES. I think i am able to encrypt using with CFB but how can I decrypt?? My main issue is CFB code for encrypting using CFB correct ??. Due to the restriction I have, I am unable to use other library.
for (int i = 0; i < VecMSG.size(); i++) {
DESEncrypt(IV, Key);
stringstream str;
str << bitset < 32 > (V[0]); //First 32 bits convert to string
str << bitset < 32 > (V[1]); //Second 32 bits covert to string and join with the first
VText2 = VText = str.str(); //Store in 2 different strings
VText = VText.substr(0, 5); //Take the most significant first 5 bits in the form of
str.str("");
bitset < 2 > mybits(VText); //covert to bits
bitset < 2 > mybits2(VecMSG[i]); //covert plaintext bits from string to bits
str << (mybits ^= mybits2); //XOR with and convert to string
VecCipher.push_back(str.str()); //Store in a different vector
str.str("");
VText2 = VText2.substr(5) + VecCipher[i]; //Remove the first 5 bits and join ciphertext to the end
V[0] = (unsigned int)VText2.substr(0,32).c_str();
V[1] = (unsigned int)VText2.substr(32).c_str();
}

Resources