Main Content

ElGamal 公開鍵暗号システム

ガロア体配列の関数 gf を使用して、ElGamal 公開鍵暗号システムを実装します。

キーの生成

多項式の次数 m を定義します。

m = 15;
q = 2^m;

原始多項式とグループ発生器を求めます。結果に再現性をもたせるために、乱数発生器シードを設定します。

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 文字であるため、1 文字あたり 7 ビットで十分です。

bitsPerChar = 7;
binMsg = int2bit(int8(text'),bitsPerChar);
numPaddedBits = m - mod(numel(binMsg),m);
if numPaddedBits == m
    numPaddedBits = 0;
end
binMsg = [binMsg; zeros(numPaddedBits,1)];
textToEncrypt = bit2int(binMsg,m);

元のメッセージを暗号化します。

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));

復号化

暗号化された元のメッセージを復号化します。

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 はビットを char メッセージに変換します。

function text = de2char(msg,bitsPerChar,m)
binDecipherText = int2bit(msg,m);
text = char(bit2int(binDecipherText(1:end-mod(numel(binDecipherText), ...
    bitsPerChar)),bitsPerChar))';
end

参考

関数

関連するトピック