Symetrische Verschlüsselung

  • Beitrags-Autor:
  • Beitrags-Kategorie:Java
  • Beitrags-Kommentare:0 Kommentare

Bei Symmetrisches Kryptosystemen nutzen Sender und Empfänger den selben Schlüssel um ihre Nachricht vor den Blicken Dritter zu schützen. Folgendes Beispiel zeigt dieses Verfahren mit ein paar Zeilen in Java.

[code lang=“java“]import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

public class SimpleCipher {
public static void main(String[] args) {
String data = „This have I thought good to deliver thee“;
// —————Encryption ———————————
byte[] encrypted = null;
byte[] iv = null;
SecretKey key = null;
try {
KeyGenerator keygen = KeyGenerator.getInstance(„DES“);
key = keygen.generateKey(); // the secret key
/*
* get cipher engine instance. DES algorithm is used and
* it requires the input data to be 8-byte sized blocks.
* To encrypt a plain text message that is not multiples
* of 8-byte blocks, the text message must be padded
* with additional bytes to make the text message to
* be multiples of 8-byte blocks.PKCS5Padding has used
* for that purpose. note that CBC is a block cipher
* mode therefore we need an initialization vector to
* chain blocks.
*/
Cipher cipher = Cipher.getInstance(„DES/CBC/PKCS5Padding“);
cipher.init(Cipher.ENCRYPT_MODE, key);
encrypted = cipher.doFinal(data.getBytes());
/*
* save the initialization vector, remember that
* we need this only when we are using cipher
* block chaining mode for encryption
*/
iv = cipher.getIV();
} catch (Exception e) {
e.printStackTrace();
}
// —————Decryption ———————————
try {
Cipher cipher = Cipher.getInstance(„DES/CBC/PKCS5Padding“);
AlgorithmParameterSpec param = new IvParameterSpec(iv);/*
* set the
* vector
* value
*/
cipher.init(Cipher.DECRYPT_MODE, key, param);
byte[] decrypted = cipher.doFinal(encrypted);
System.out.println(new String(decrypted));
} catch (Exception e) {
e.printStackTrace();
}
}
}[/code]

Schreibe einen Kommentar

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.