Криптографическая система открытого ключа ElGamal

Используйте функцию массива Поля Галуа, gf, реализовывать криптографическую систему открытого ключа ElGamal.

Генерация ключей

Задайте полиномиальную степень, m.

m = 15;
q = 2^m;

Найдите примитивный полином и генератор группы. Установите seed генератора случайных чисел приводить к повторяемому результату.

poly = primpoly(m,'nodisplay');

primeFactors = unique(factor(2^m-1));
rng(123456);
while 1
    g = gf(randi([1,q-1]),m,poly);
    isPrimitive = true;
    for i = 1:length(primeFactors)
        if g^((q-1)/primeFactors(i)) == gf(1,m,poly)
            isPrimitive = false;
            break;
        end
    end
    if isPrimitive
        break;
    end
end

Создайте закрытые и открытые ключи.

privateKey = 12;
publicKey = {g,g^privateKey,poly};

Шифрование

Создайте и отобразите исходное сообщение.

text = ['The Fourier transform decomposes a function of time (a signal)' newline ...
    'into the frequencies that make it up, in a way similar to how a' newline ...
    'musical chord can be expressed as the amplitude (or loudness) of' newline ...
    'its constituent notes.'];
disp(text);
The Fourier transform decomposes a function of time (a signal)
into the frequencies that make it up, in a way similar to how a
musical chord can be expressed as the amplitude (or loudness) of
its constituent notes.

Преобразуйте сообщение в двоичный файл и сгруппируйте их каждый m биты. Сообщение использует символы ASCII. Поскольку таблица ASCII имеет 128 символов, семь битов за символ достаточно.

bitsPerChar = 7;
binMsg = de2bi(int8(text),bitsPerChar,'left-msb')';
numPaddedBits = m - mod(numel(binMsg),m);
if numPaddedBits == m
    numPaddedBits = 0;
end
binMsg = [binMsg(:); zeros(numPaddedBits,1)];
textToEncrypt = bi2de(reshape(binMsg,[],m),'left-msb');

Зашифруйте исходное сообщение.

cipherText = gf(zeros(length(textToEncrypt),2),m,poly);

for i = 1:length(textToEncrypt)
    k = randi([1 2^m-2]);
    cipherText(i,:) = [publicKey{1}^k, ...
        gf(textToEncrypt(i),m,poly)*publicKey{2}^k];
end

Отобразите зашифрованное сообщение.

tmp = cipherText.x;
disp(de2char(tmp(:,2),bitsPerChar,m));
Y7cyg^]OT9*3a~sCoxEWsL}LWpxcWPX@/C$#Y`f&IM8i?&\ODRn/91D
aQ @LZM5'hGpR'\N>6/cfa&nXF1:P%uwmGp6j!]%"&/LTHX$-qO>]JTMdRT'K(p\ CQ>e(HNn9358M,9\VDtMV'
9S9k[#0'Fs=:p

Дешифрование

Дешифруйте зашифрованное исходное сообщение.

decipherText = gf(zeros(size(cipherText,1),1),m,poly);
for i = 1:size(cipherText,1)
    decipherText(i) = cipherText(i,2) * cipherText(i,1)^(-privateKey);
end

Отобразите дешифрованное сообщение.

disp(de2char(decipherText.x,bitsPerChar,m));
The Fourier transform decomposes a function of time (a signal)
into the frequencies that make it up, in a way similar to how a
musical chord can be expressed as the amplitude (or loudness) of
its constituent notes.

Поддерживание функции

de2char преобразует биты в символьные сообщения.

function text = de2char(msg,bitsPerChar,m)
binDecipherText = de2bi(msg,m,'left-msb');
text = char(bi2de(reshape(binDecipherText(1:end-mod(numel(binDecipherText), ...
    bitsPerChar)),bitsPerChar,[])','left-msb'))';
end

Смотрите также

Функции

Похожие темы

Для просмотра документации необходимо авторизоваться на сайте