Verschlüsseln mit bouncing castle

Lucaaa

Bekanntes Mitglied
Hallo!
In meiner vorherigen Frage habe ich nach crypto libs gesucht. Dort wurde mir Bouncing Castle vorgeschlagen. Was ich auf der Website gesehen habe sind schonmal ganz gut aus, Mein Problem ist nur, dass ich nicht ganz kapiere wie ich nun (einen String) verschlüsseln kann.
Ich möchte den Key auch nicht aus einem Byte[] generieren, sondern mit einem KeyGenerator wie bei der Standard Java.crypto.
Ein Beispiel oder so wäre sehr hilfreich.
Danke schon mal!
 

AndyJ

Bekanntes Mitglied
Die Bouncycastle Library ist (unter anderem) eine JCE-provider Implementierung. An der Art und Weise wie verschluesselt wird aendert sich dadurch gar nichts. Man hat lediglich mehr Algorithmen zur Verfuegung. Hier ein paar Beispiele dazu:

Symmetrische Verschluesselung kann man in zwei Klassen unterteilen, Blockverschluesselung und Streamverschluesselung. Hier ein Block Cipher:
Code:
package info.junius.test;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class SymmetricBlockCipher {

    // basics:
    // text + key ==> cipher text
    // cipher text + key ==> plain text
    public static void main ( String[] args ) {
        byte[] cipherText = null;
        byte[] initVector = null;
        byte[] rawKey = null;
        // generate a key and a cipher and encode a document
        try {
            String plainText = "This is some top secret text!";
            KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
            SecretKey key = keyGenerator.generateKey();
            rawKey = key.getEncoded();
            SecretKeySpec keySpecification = new SecretKeySpec(rawKey, "DES");
            // des cipher with Cipher Block Chaining mode and pkcs5 padding scheme
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            // initialise cipher 
            cipher.init(Cipher.ENCRYPT_MODE, keySpecification, new SecureRandom());
            initVector = cipher.getIV();
            // encrypt (call update several times to process multiple chunks. every chunk gets processed individually)
            // byte[] cipherTextChunk1 = cipher.update(plainText.getBytes("UTF-8"));
            // byte[] cipherTextChunk2 = cipher.update(plainText2.getBytes("UTF-8"));
            // byte[] cipherText = cipher.doFinal();
            // System.out.println("cipherTextChunk1:      " + Arrays.toString(cipherTextChunk1));
            // System.out.println("cipherTextChunk2:      " + Arrays.toString(cipherTextChunk2));
            // System.out.println("cipherText:            " + Arrays.toString(cipherText));
            // optional, only a single call
            cipherText = cipher.doFinal(plainText.getBytes("UTF-8"));
            // output
            System.out.println("Cipher blocksize:      " + cipher.getBlockSize());
            System.out.println("Cipher algorithm:      " + cipher.getAlgorithm());
            System.out.println("Cipher output size:    " + cipher.getOutputSize(plainText.length()));
            System.out.println("Cipher parameters:     " + cipher.getParameters());
            System.out.println("Cipher provider:       " + cipher.getProvider());
            System.out.println("Plain text:            " + plainText);
            System.out.println("Cipher text:           " + Arrays.toString(cipherText));
            System.out.println("Initialisation vector: " + Arrays.toString(initVector));
            System.out.println("******************************************************************");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // now decrypt the cipher using data created above, i.e. cipher, rawKey and initialisation vector
        // also necessary to know:
        // algorithm, mode, padding scheme, e.g. DES/CBC/PKCS5Padding
        try {
            // create key specification
            SecretKeySpec keySpecification = new SecretKeySpec(rawKey, "DES");
            // initialisation vector as a parameter specification
            IvParameterSpec iv = new IvParameterSpec(initVector);
            // create cipher, same as for encryption
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            // initialise cipher
            cipher.init(Cipher.DECRYPT_MODE, keySpecification, iv);
            byte[] plainText = cipher.doFinal(cipherText);
            String decrypted = new String(plainText);
            // output
            System.out.println("Raw Key:               " + Arrays.toString(rawKey));
            System.out.println("Cipher blocksize:      " + cipher.getBlockSize());
            System.out.println("Cipher algorithm:      " + cipher.getAlgorithm());
            System.out.println("Cipher parameters:     " + cipher.getParameters());
            System.out.println("Cipher provider:       " + cipher.getProvider());
            System.out.println("Cipher text:           " + Arrays.toString(cipherText));
            System.out.println("Initialisation vector: " + Arrays.toString(initVector));
            System.out.println("Decrypted text:        " + decrypted);
            System.out.println("******************************************************************");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
    }
}

Und hier ein Stream Cipher:
Code:
package info.junius.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class SymmetricStreamCipher {

    // basics:
    // text + key ==> cipher text
    // cipher text + key ==> plain text
    public static void main ( String[] args ) {
        byte[] cipherText = null;
        byte[] initVector = null;
        byte[] rawKey = null;
        // generate a key and a cipher and encrypt a document
        try {
            String plainText = "This is some top secret text!";
            KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
            SecretKey key = keyGenerator.generateKey();
            rawKey = key.getEncoded();
            SecretKeySpec keySpecification = new SecretKeySpec(rawKey, "DES");
            // des cipher with Cipher Feedback mode, 8 bit and pkcs5 padding scheme
            Cipher cipher = Cipher.getInstance("DES/CFB8/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpecification, new SecureRandom());
            // get input stream for string
            InputStream is = new ByteArrayInputStream(plainText.getBytes());
            // create output stream for cipher
            OutputStream os = new ByteArrayOutputStream();
            // create cipher input stream using plain text and cipher as input
            CipherInputStream cis = new CipherInputStream(is, cipher);
            // read from cipherinputstream and write to outputstream
            byte[] cipherBytes = new byte[2];
            int i = 0;
            while ( (i = cis.read(cipherBytes)) != -1) {
                os.write(    cipherBytes, 0, i);
                System.out.println(Arrays.toString( ((ByteArrayOutputStream)os).toByteArray()));
            }
            cis.close();
            is.close();
            os.close();
            initVector = cipher.getIV();
            cipherText = ((ByteArrayOutputStream)os).toByteArray();
            // output
            System.out.println("Cipher blocksize:      " + cipher.getBlockSize());
            System.out.println("Cipher algorithm:      " + cipher.getAlgorithm());
            System.out.println("Cipher output size:    " + cipher.getOutputSize(plainText.length()));
            System.out.println("Cipher parameters:     " + cipher.getParameters());
            System.out.println("Cipher provider:       " + cipher.getProvider());
            System.out.println("Plain text:            " + plainText);
            System.out.println("Cipher text:           " + Arrays.toString(cipherText));
            System.out.println("Initialisation vector: " + Arrays.toString(initVector));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // now decrypt the cipher using data created above, i.e. cipher, rawKey and initialisation vector
        // also necessary to know:
        // algorithm, mode, padding scheme, e.g. DES/CFB8/PKCS5Padding
        try {
            // create key specification
            SecretKeySpec keySpecification = new SecretKeySpec(rawKey, "DES");
            // initialisation vector as a parameter specification
            IvParameterSpec iv = new IvParameterSpec(initVector);
            // create cipher, same as for encryption
            Cipher cipher = Cipher.getInstance("DES/CFB8/PKCS5Padding");
            // initialise cipher
            cipher.init(Cipher.DECRYPT_MODE, keySpecification, iv);
            // get input stream for string
            InputStream is = new ByteArrayInputStream(cipherText);
            // create output stream for text
            OutputStream os = new ByteArrayOutputStream();
            // create cipher input stream using cipher text and cipher as input
            CipherInputStream cis = new CipherInputStream(is, cipher);
            // read from cipherinputstream and write to outputstream
            byte[] cipherBytes = new byte[2];
            int i = 0;
            while ( (i = cis.read(cipherBytes)) != -1) {
                os.write(    cipherBytes, 0, i);
                System.out.println(Arrays.toString( ((ByteArrayOutputStream)os).toByteArray()));
            }
            cis.close();
            is.close();
            os.close();
            byte[] decrypted = ((ByteArrayOutputStream)os).toByteArray();
            String decryptedText = new String(decrypted);
            // output
            System.out.println("Raw Key:               " + Arrays.toString(rawKey));
            System.out.println("Cipher blocksize:      " + cipher.getBlockSize());
            System.out.println("Cipher algorithm:      " + cipher.getAlgorithm());
            System.out.println("Cipher parameters:     " + cipher.getParameters());
            System.out.println("Cipher provider:       " + cipher.getProvider());
            System.out.println("Cipher text:           " + Arrays.toString(cipherText));
            System.out.println("Initialisation vector: " + Arrays.toString(initVector));
            System.out.println("Decrypted text, bytes: " + Arrays.toString(decrypted));
            System.out.println("Decrypted text:        " + decryptedText);
            System.out.println("******************************************************************");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Wenn du wissen willst was dir so alles zur Verfuegung steht:
Code:
package info.junius.test;

import java.security.Provider;
import java.security.Provider.Service;
import java.security.Security;

public class ListProviders {

    public static void main ( String[] args ) {
        Provider[] providers = Security.getProviders();
        for (Provider provider : providers) {
            System.out.println("toString():     " + provider);
            System.out.println("Provider Class: " + provider.getClass().getCanonicalName());
            System.out.println("Provider Name:  " + provider.getName());
            System.out.println("Provider Info:  " + provider.getInfo());
            System.out.println("Number of Keys: " + provider.size());
            System.out.println("Version:        " + provider.getVersion());
            System.out.println("Supported Algorithms-----------------------");
            for (Service service : provider.getServices()) {
                System.out.println("\t" + service.getAlgorithm() + ", type: " + service.getType() + ", implementation: " + service.getClassName());
            }
            System.out.println("*******************************************");
        }
    }
}

Mit der BC Library ist der Output obigen Codes erheblich laenger. Die Verschluesselungsstaerke war in Java frueher ziemlich beschraenkt, man musste schon die "Unlimited Strength Policy Files" installieren, um wirklich verschluesseln zu koennen. Ich glaube aber, dass die diesen Unsinn jetzt endlich abgeschafft haben.

Cheers,
Andy
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
H String verschlüsseln - eigener Algorithmus Java Basics - Anfänger-Themen 104
I SHA512 verschlüsseln und dann wieder auslesen? Java Basics - Anfänger-Themen 35
T String simpel aber sicher verschlüsseln Java Basics - Anfänger-Themen 5
U Passwort verschlüsseln schlägt fehl Java Basics - Anfänger-Themen 3
L Text verschlüsseln Java Basics - Anfänger-Themen 13
S Strings verschlüsseln und entschlüsseln?! Java Basics - Anfänger-Themen 6
H Erste Schritte Verschlüsseln Java Basics - Anfänger-Themen 13
O Java Dateien verschlüsseln? Java Basics - Anfänger-Themen 22
B String verschlüsseln - Applet - ohne BASE64 Java Basics - Anfänger-Themen 7
R Server-Daten sichern/verschlüsseln Java Basics - Anfänger-Themen 10
P Sensible Daten Speichern/Verschlüsseln von serialisiertem Objekt Java Basics - Anfänger-Themen 5
-horn- Java-Bytecode und Outputs verschlüsseln? Java Basics - Anfänger-Themen 3
E Verschlüsseln und FileWrite Java Basics - Anfänger-Themen 6
S String mit Hilfe von Array verschlüsseln Java Basics - Anfänger-Themen 19
F Algorithm zum Verschlüsseln und Entschlüsseln Java Basics - Anfänger-Themen 6
S Nummern verschlüsseln, prüfen ob vorhanden in Datenbank Java Basics - Anfänger-Themen 2
B Strings verschlüsseln Java Basics - Anfänger-Themen 6
H verschlüsseln von daten Java Basics - Anfänger-Themen 2
D daten verschlüsseln Java Basics - Anfänger-Themen 4
D Passwort verschlüsseln mit MD5 Java Basics - Anfänger-Themen 30
A MD5 verschlüsseln Java Basics - Anfänger-Themen 3
A DSA und Base64 Verschlüsseln und Entschlüsseln Java Basics - Anfänger-Themen 4
S "Verschlüsseln" anderer Dateien! Java Basics - Anfänger-Themen 19
L Datei verschlüsseln Java Basics - Anfänger-Themen 9
Jxhnny.lpz bouncing Ball (Brick-Breaker-Game) Java Basics - Anfänger-Themen 1
Jxhnny.lpz bouncing ball / abprallender Ball Java Basics - Anfänger-Themen 11
A Bouncing Ball bis er ruht Java Basics - Anfänger-Themen 6
J Das schöne Bouncing Ball Beispiel. Java Basics - Anfänger-Themen 20

Ähnliche Java Themen

Neue Themen


Oben