One Time Pad (Algorithmen)
In dieser Aufgabe soll ein beliebiger Text durch das One Time Pad mit einem beliebigen Schlüssel verschlüsselt/ entschlüsselt werden. Dabei soll im Voraus gewählt werden können ob ver- oder entschlüsselt werden soll. Wenn der Schlüssel zu kurz ist, soll eine Fehlermeldung ausgegeben werden. Ist der Schlüssel zu lang, soll einfach der erste Teil genutzt werden.
Zusatz: Generator für zufällige Schlüssel, grafische Oberfläche, Schutz vor 2x verwendeten Schlüsseln
0 Kommentare
6 Lösung(en)
import java.io.*;
/******************************************************************************
* <code> XORKrypt
* </code>
* One-time-pad
*
* @author Philipp Gressly (phi)
* @version 0.99 -- 1999-Nov-23 08:00
*/
/* History: 1999-Nov-23 08:00 (first implementations)
*
* Bugs : none known.
*******************************************************************************/
public class XORKrypt
{
byte key[];
/******************************************************************************
* <code> XORKrypt
* </code>
*
*
* @param
* @return
*/
/* History: 1999-Nov-23 08:00 (first implementations)
*
* Bugs : none known.
*******************************************************************************/
public XORKrypt(File kFile) throws IOException
{
RandomAccessFile raf = new RandomAccessFile(kFile, "r");
long length = raf.length();
this.key = new byte[(int) length];
raf.read(this.key);
raf.close();
} // end method: XORKrypt
/******************************************************************************
* <code> enkrypt
* </code>
*
*
* @param
* @return
*/
/* History: 1999-Nov-23 08:08 (first implementations)
*
* Bugs : none known.
*******************************************************************************/
private void enkrypt(File inFile, File outFile) throws IOException
{
FileInputStream fis = new FileInputStream(inFile);
FileOutputStream fos = new FileOutputStream(outFile);
int read = fis.read();
long pos = 0;
// Anstelle einer Fehlermeldung wird der Schlüssel
// hier einfach mehrfach verwendet.
// Dies entspricht der Komplexität der Vigenere Chiffre.
// Ist das Keyfile länger als der Klartext, dann
// treten keine Probleme auf.
while(read >= 0)
{
int modPos = (int) (pos % key.length);
fos.write(read ^ key[modPos]);
pos++;
read = fis.read();
}
fos.close();
fis.close();
} // end method: enkrypt
/******************************************************************************
* <code> enkrypt
* </code>
*
*
* @param inFileName
* @param outFileName
*/
/* History: 2000-Aug-30 13:32 (first implementations)
*
* Bugs : none known.
*******************************************************************************/
public void enkrypt(String inFileName, String outFileName) throws Exception
{
File inFile = new File(inFileName );
File outFile = new File(outFileName);
enkrypt(inFile, outFile);
} // end method: enkrypt
/******************************************************************************
* <code> main
* </code>
*
*
* @param
* @return
*/
/* History: 1999-Nov-23 08:00 (first implementations)
*
* Bugs : none known.
*******************************************************************************/
public static void main(String[] args)
{
boolean multi = false;
XORKrypt xorKrypt;
if(args.length != 3)
{
System.out.println("Usage: XORKrypt <keyfile> <inpostfix | infile> <outfilemask>");
System.out.println("Example 1: java XORKrypt F1.key original.txt krypt.txt");
System.out.println("Example 2: java XORKrypt F1.key \"*.txt\" \"*.kpt\"");
}
else
{
File keyFile = new File(args[0]);
if(args[1].startsWith("*.") && args[2].startsWith("*."))
multi = true;
try {
xorKrypt = new XORKrypt(keyFile);
}
catch(IOException ioe)
{
System.out.println("Error in Krypt-File: " + ioe);
return;
}
if(! multi) {
try {
xorKrypt.enkrypt(args[1], args[2]);
} catch (Exception e) {
System.out.println("Exception while converting: " + e);
}
}
else {
final String inFilterString = args[1].substring(1);
final String outFilterString = args[2].substring(1);
System.out.println("inFilterstring = " + inFilterString);
FilenameFilter fnf = new FilenameFilter() {
public boolean accept(File dir, String name)
{
return name.endsWith(inFilterString);
}
};
File dir = new File (".");
String inFileNames[] = dir.list(fnf);
for(int i = 0; i < inFileNames.length; i++)
{
System.out.println("InFileName = " + inFileNames[i]);
int li = inFileNames[i].lastIndexOf(inFilterString);
String base = inFileNames[i].substring(0, li);
//System.out.println("BaseFileName = " + base);
String outFileName = base + outFilterString;
System.out.println("processing " + outFileName);
try {
xorKrypt.enkrypt(inFileNames[i], outFileName);
} catch (Exception ex) {
System.out.println("Exception while converting: " + ex);
}
}
}
}
} // end main
} // end class: XORKrypt
Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)
package Aufgaben.Encryption;
import java.util.Random;
import java.util.Scanner;
public class OTPEncryption
{
public static void main(String[] args)
{
System.out.println("Geben Sie einen zu verschlüsselnden Text ein: ");
Scanner scan = new Scanner(System.in);
String teststring = scan.nextLine();
System.out.println(teststring + "\n");
StringBuilder keybuilder = new StringBuilder();
for(int i = 0; i < teststring.length(); i++)
{
keybuilder.append((char)(new Random().nextInt(65535)));
}
System.out.println("Verwendeter Schlüssel: " + keybuilder + "\n");
String key = new String(keybuilder);
String encryptedString = crypt(teststring, key, true);
System.out.println("Codierter Text: " + encryptedString + "\n");
String decryptedString = crypt(encryptedString, key, false);
System.out.println("Decodierter Text: " + decryptedString + "\n");
}
public static String crypt(String text, String key, boolean encrypt)
{
StringBuilder encrypted = new StringBuilder();
char dummy;
for(int i = 0; i < text.length(); i++)
{
dummy = text.charAt(i);
if(encrypt)
{
dummy += key.charAt(i);
}
else
{
dummy -= key.charAt(i);
}
encrypted.append(dummy);
}
return new String(encrypted);
}
}
Lösung von: Name nicht veröffentlicht
using System;
using System.Linq;
namespace One_Time_Pad
{
class Program
{
static void Main(string[] args)
{
while(true)
{
Console.WriteLine("[V]erschlüsseln / [E]ntschlüsseln?");
string Type = Console.ReadLine().ToLower();
if (Type != "v" && Type != "e") { Console.WriteLine("Der Input ist ungültig."); continue; }
Console.WriteLine("Schreibe den Text und den Schlüssel (Text;Schlüssel)");
string[] Inhalt = Console.ReadLine().Split(';');
string Text = "";
int Space = 0;
if (Inhalt[0].Replace(" ",string.Empty).Length > Inhalt[1].Length) { Console.WriteLine("Der Schlüssel darf nicht kürzer als der Text sein"); continue; }
if (Type == "v")
{
for (int i = 0; i < Inhalt[0].Length; i++)
{
int ASCII = Convert.ToInt32(Convert.ToChar(Inhalt[0].ToLower()[i]));
if (ASCII != 32)
{
ASCII += Convert.ToChar(Inhalt[1].ToLower()[i-Space]) - 96;
if (ASCII - 96 > 26)
{
ASCII -= 26;
}
}
else Space++;
Text += Convert.ToChar(ASCII);
}
}
else if (Type == "e")
{
for (int i = 0; i < Inhalt[0].Length; i++)
{
int ASCII = Convert.ToInt32(Convert.ToChar(Inhalt[0].ToLower()[i]));
if (ASCII != 32)
{
ASCII -= Convert.ToChar(Inhalt[1].ToLower()[i-Space]) - 96;
if (ASCII - 96 <= 0)
{
ASCII += 26;
}
}
else Space++;
Text += Convert.ToChar(ASCII);
}
}
Console.WriteLine(Text);
Console.WriteLine("------------------------------------------");
}
}
}
}
Lösung von: Tobias Golz (Wilhelm Büchner Hochschule)
def crypt(message,keyStr,mode):
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 .'
KEYS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-_'
translated = ''
keyIndex = 1
global result
for symbol in message:
if keyIndex > len(keyStr):
keyIndex = 1
key = KEYS.find(keyStr[keyIndex-1]) +1
keyIndex += 1
if symbol in SYMBOLS:
symbolIndex = SYMBOLS.find(symbol)
if mode == 'encrypt':
translatedIndex = symbolIndex + key
elif mode == 'decrypt':
translatedIndex = symbolIndex - key
if translatedIndex >= len(SYMBOLS):
translatedIndex = translatedIndex - len(SYMBOLS)
elif translatedIndex < 0:
translatedIndex = translatedIndex + len(SYMBOLS)
translated = translated + SYMBOLS[translatedIndex]
else:
translated = translated + symbol
print(translated)
result = translated
message = 'In dieser Aufgabe soll ein beliebiger Text mit einem \
beliebigen Schlüssel verschlüsselt/ entschlüsselt werden.'
keyStr = 'abaaaaaaay'
crypt(message, keyStr, 'encrypt')
crypt(result, keyStr, 'decrypt')
import secrets
keyStr = secrets.token_urlsafe(8) ;print('Key:', keyStr) #8 byte
crypt(message, keyStr, 'encrypt')
crypt(result, keyStr, 'decrypt')
Lösung von: Alex Groeg (Freies Lernen)
// C++ 14 | VS-2022
#include <iostream>
#include <string>
enum class MODE { decrypt = -1, encrypt = 1};
const std::string CHR{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-_.!? " };
const int LEN{ (int)CHR.length() };
std::string get_key(int len) {
std::string k{ };
for (size_t i{ 0 }; i < len; i++)
k.push_back(CHR[rand() % LEN]);
return k;
}
std::string de_encrypt(const MODE mod, const std::string& txt, const std::string& key) {
if (txt.length() != key.length()) return "unusable key";
std::string g{};
const auto fpos{ [&](char c) {auto pos = CHR.find(c); if (pos != std::string::npos) return (int)pos; return -1; } };
for (auto i{ 0 }; i < txt.length(); i++) {
const auto f1{ fpos(txt[i]) }, f2{ fpos(key[i]) };
if (f1 == -1 || f2 == -1) return "char not found";
auto t{ f1 + (int)mod * f2 };
g.push_back(MODE::encrypt == mod ? (t > LEN ? CHR[(t -= LEN)] : CHR[t]) : (t < 0 ? CHR[t += LEN] : CHR[t]));
}
return g;
}
int main() {
srand((int)time(nullptr));
const std::string txt{ "Angriff im Morgengrauen!" };
const std::string key{ get_key((int)txt.length()) };
const auto ec{ de_encrypt(MODE::encrypt, txt, key) };
const auto dc{ de_encrypt(MODE::decrypt, ec, key) };
std::cout << "text:\t\t" << txt << "\n";
std::cout << "key:\t\t" << key << "\n";
std::cout << "encrypt:\t" << ec << "\n";
std::cout << "decrypt:\t" << dc << "\n";
}
Lösung von: Jens Kelm (@JKooP)
// beliebig anpassbar
const VALID_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÜ' +
'abcdefghijklmnopqrstuvwxyzäöüß' +
'1234567890!"§$%&/()=?*+;:_,.-';
// eingabemaske
document.write(`
<h1>Unufoja ?ifro</h1>
<p>
<label for="input">Enigo:</label><br>
<textarea id="input"></textarea>
</p><p>
<label for="key">?ifrilo:</label><br>
<input type="text" id="key"></input>
<button onclick="getRandomKey()">Hazarda ?ifro</button>
</p><p>
<label for="output">Eligo:</label><br>
<textarea id="output" onchange="go()"></textarea>
</p><p>
<input type="radio" id="encrypt" name="crypt" checked>
<label for="encrypt">?ifri</label>
<input type="radio" id="decrypt" name="crypt">
<label for="encrypt">Mal?ifri</label>
</p><button onclick="go()"><b>Ek</b></button></p>
<p><button onclick="clearUsed()">Nuligu uzitajn ?ifrilojn</button></p>
`);
function vigenere(txt, key, enc = true) {
let keyInd = 0,
out = '';
// $txt vorbereiten:
// leerzeichen durch _ ersetzn
txt = txt.replace(/ /g, '_');
// ungültige zeichen entfernen
let r = VALID_CHARS
.replace('/', '\\/')
.replace('-', '\\-');
txt = txt.replace(new RegExp(`[^${r}]`, 'g'), '');
txt = txt.split(''); key = key.split('');
// ver-/entschlüsselung
for (char of txt) {
let disc = VALID_CHARS.slice(VALID_CHARS.indexOf(key[keyInd])) +
VALID_CHARS.slice(0, VALID_CHARS.indexOf(key[keyInd]-1));
out += (enc) ? disc.charAt(VALID_CHARS.indexOf(char))
: VALID_CHARS.charAt(disc.indexOf(char));
keyInd = (keyInd + 1) % key.length;
}
return out;
}
// eigentlich nicht zweckdienlich, verwendete schlüssel
// auf die festplatte zu speichern, deshalb nur zur demonstration
let used = (localStorage.usedOneTimePads) ?
localStorage.usedOneTimePads.split(' ') : [];
let input = document.getElementById('input'),
output = document.getElementById('output'),
key = document.getElementById('key'),
encrypt = document.getElementById('encrypt');
function getRandomKey() {
let out = '';
if (input.value.length == 0) console.warn('Mankas enigo.');
for (let i = 0; i < input.value.length; i++)
out += VALID_CHARS.charAt(Math.floor(Math.random() * VALID_CHARS.length));
if (used.includes(out)) getRandomKey();
else key.value = out;
}
function check() {
switch (true) {
case (input.value.length == 0):
alert('Mankas enigo');
return false;
break;
case (key.value.length == 0):
alert('Mankas ?ifrilo');
return false;
break;
case (key.value.length < input.value.length):
alert('?ifrilo estu minimume samlonga kiel enigo.');
return false;
break;
case (used.includes(key.value)):
alert('?ifrilo jam uzita.');
return false;
break;
}
return true;
}
function clearUsed() {
localStorage.removeItem('usedOneTimePads');
used = [];
}
function go() {
if (check()) {
output.value = vigenere(input.value, key.value, encrypt.checked);
used.push(key.value);
}
}
window.onunload = function() { localStorage.usedOneTimePads = used.join(' '); }
Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)
Verifikation/Checksumme:
Unverschlüsselt: "Hello World"
Schlüssel: "abaaaaaaay"
Verschlüsselt: "Igmmp Xpsmc" oder "igmmppsmc"
Aktionen
Neue Lösung hinzufügen
Bewertung
Durchschnittliche Bewertung: