Mange tak for koden!
mvh
John
> > Hej,
> > Der skulle vel ikke findes en som har en kodestump, eller som kender et
> godt
> > eksempel på kryptering i java?
>
> Jeg har bedst erfaring med open-jce
http://www.openjce.org/ som i
modsætning
> til SUNs JCE også virker 100% udenfor USA, og ikke kræver alle mulige
> underlige ændringer i opsætningen.
>
> Jeg har vedlagt tre filer, der henholdsvis kan generere et sæt
assymetriske
> nøgler,
> kryptere en fil, og dekryptere filen igen.
>
> Med assymetriske nøgler, bruger man den offentlige (publicKey) til at
> kryptere med, og den private til at dekryptere.
>
> Den væsentligste forskel på encrypt og decrypt programmerne er faktisk
> indlæsningen af nøglerne. En publicKey er gemt i X509 format, hvorimod en
> privateKey er gemt i PKCS8 format.
>
> Derudover er det kun selve krypteringen/dekrypteringen der adskiller sig,
> med disse to linjer:
>
> coding.init(Cipher.DECRYPT_MODE, privateKey);
> coding.init(Cipher.ENCRYPT_MODE, publicKey);
>
> I eksemplet benytter jeg RSA/ECB kryptering med PKCS1 padding. Jeg kan
ikke
> huske hvad forskellene på de forskellige standarder egentlig er, men du
kan
> jo altid eksperimentere...
>
> mvh
> Peter Lind
>
> ------------------------
> Fil1: GenerateKeys.java
> ------------------------
>
> import java.io.*;
> import java.security.*;
> import java.security.spec.*;
> import java.security.interfaces.*;
> import javax.crypto.*;
> import javax.crypto.spec.*;
> import javax.crypto.interfaces.*;
> import au.net.aba.crypto.provider.*;
>
> /**
> * GenerateKeys is used for generating keys for encrypting or signing
> datafiles.
> * It always generates a set of keys, a public and a private.
> * It can be used as a standalone application, or as a class from other
> applications.
> *
> * A typical usage-pattern is as follows:
> * 1) construct a GenerateKeys object
> * 2) use setType to select the type of keys you wish to generate,
SIGN_KEY
> or CRYPTO_KEY
> * 3) use generate to generate the keyset
> * 4) use savePublic to save the public key to an encoded file
> * 5) use savePrivate to save the private key to an encoded file
> *
> *
> * @author Peter Lind
> * @version 1.0 - 15. august 2000
> */
> public class GenerateKeys
> {
> public final static int SIGN_KEY = 0;
> public final static int CRYPTO_KEY = 1;
>
> private PrivateKey privateKey;
> private PublicKey publicKey;
>
> private KeyPairGenerator keygenerator;
>
>
> /**
> * Default constructor
> *
> */
> public GenerateKeys( )
> {
>
> }
>
>
> /**
> * Set the type of key to be generated.
> *
> * Crypto or Signature.
> *
> */
> public void setType( int keytype ) throws NoSuchAlgorithmException
> {
> switch( keytype )
> {
> case SIGN_KEY: // Create a DSA keyset for signatures
> keygenerator =
KeyPairGenerator.getInstance("DSA");
> break;
>
> case CRYPTO_KEY: // Create a RSA keyset for cryptography
> keygenerator = new RSAKeyPairGenerator();
> break;
> }
> }
>
>
> /**
> * Generate a set of keys.
> *
> */
> public void generate() throws NoSuchAlgorithmException
> {
> SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
> keygenerator.initialize( 1024, random );
>
> KeyPair pair = keygenerator.generateKeyPair();
> privateKey = pair.getPrivate();
> publicKey = pair.getPublic();
> }
>
>
> /**
> * Saves the encoded private key to a given file.
> *
> */
> public void savePrivate( FileOutputStream privatefile ) throws
IOException
> {
> byte[] keyv = privateKey.getEncoded();
> privatefile.write(keyv);
> privatefile.close();
>
> }
>
>
> /**
> * Saves the encoded public key to a given file.
> *
> */
> public void savePublic( FileOutputStream publicfile ) throws IOException
> {
> byte[] key = publicKey.getEncoded();
> publicfile.write(key);
> publicfile.close();
> }
>
>
> /**
> * For application use
> *
> * Call the application as:
> * Generatekeys 'type' publickeyfile privatekeyfile
> *
> * where 'type' is crypto or signature
> *
> */
> public static void main(String[] args)
> {
> if (args.length != 3)
> {
> System.out.println("Usage: Generatekeys type publicfile
privatefile");
> }
> else try
> {
> GenerateKeys generator = new GenerateKeys( );
>
> if( args[0].charAt(0) == 'C' || args[0].charAt(0) == 'c' )
> generator.setType( GenerateKeys.CRYPTO_KEY );
> if( args[0].charAt(0) == 'S' || args[0].charAt(0) == 's' )
> generator.setType( GenerateKeys.SIGN_KEY );
>
> generator.generate( );
> generator.savePublic( new FileOutputStream(args[1]) );
> generator.savePrivate( new FileOutputStream(args[2]) );
>
> }
> catch (Exception e)
> {
> System.err.println("Caught exception " + e.toString());
> }
> }
>
>
> }
>
> ------------------
> Fil2: Encrypt.java
> ------------------
>
> import java.io.*;
> import java.security.*;
> import java.security.spec.*;
> import javax.crypto.*;
> import au.net.aba.crypto.provider.*;
>
> /**
> * Encrypt is used for encrypting files.
> * It can be used as a standalone application, or as a class from other
> applications.
> *
> * A typical usage-pattern is as follows:
> * 1) construct an Encrypt object
> * 2) use loadKey to load the public encryption key
> * 3) use loadData to load the (plaintext) data to be encrypted
> * 4) use encrypt to encrypt the data
> * 5) use saveData to save the encrypted (cipher) data
> *
> *
> * @author Peter Lind
> * @version 1.0 - 15. august 2000
> */
> public class Encrypt
> {
> private PublicKey publicKey;
> private byte[] plainText;
> private byte[] cipherText;
>
>
> /**
> * Default constructor.
> *
> */
> public Encrypt( )
> {
> Security.addProvider(new ABAProvider());
> }
>
>
> /**
> * Loads the encoded key from a file and creates a publicKey object.
> *
> */
> public void loadKey( FileInputStream keyFile ) throws IOException,
> InvalidKeySpecException
> {
> // read the public key from file
> byte[] encodedKey = new byte[keyFile.available()];
> keyFile.read(encodedKey);
> keyFile.close();
>
> // Convert the encoded key (in X509 format) to a real keyobject
> X509EncodedKeySpec codedKey = new X509EncodedKeySpec( encodedKey );
> try
> {
> KeyFactory keyfactory = KeyFactory.getInstance("RSA");
> publicKey = keyfactory.generatePublic( codedKey );
> }
> catch( java.security.NoSuchAlgorithmException nsaEx )
> {
> System.out.println("Internal Error - Encrypt - loadkey, RSA unknown
> ");
> }
>
>
>
> // now the publicKey contains a real public key !
> }
>
>
> /**
> * Loads a plaintext file as a bytestream.
> *
> */
> public void loadData( FileInputStream plainFile) throws IOException,
> InvalidKeyException
> {
> plainText = new byte[plainFile.available()];
> plainFile.read(plainText);
> plainFile.close();
> }
>
>
> public byte[] getData()
> {
> return cipherText;
> }
>
>
> /**
> * Saves the encrypted cipher bytestream to a file.
> *
> */
> public void saveData( File cipherFile ) throws IOException
> {
> saveData( new FileOutputStream( cipherFile ) );
> }
>
>
>
> public void saveData( FileOutputStream cipherFile ) throws IOException
> {
> cipherFile.write(cipherText);
> cipherFile.close();
> }
>
>
> /**
> * Encrypts the loaded data with the loaded key.
> *
> */
> public void encrypt() throws InvalidKeyException,
> IllegalBlockSizeException, NoSuchPaddingException, BadPaddingException
> {
> // Setup cipher object
> try
> {
> Cipher coding = Cipher.getInstance("RSA/ECB/PKCS1Padding");
>
> // encrypt cipher with the public key
> coding.init(Cipher.ENCRYPT_MODE, publicKey);
>
> cipherText = coding.doFinal( plainText );
> }
> catch( NoSuchAlgorithmException nsaEx )
> {
> System.out.println("Internal Error - no such algorithm:
> RSA/ECB/PKCS1Padding ");
> }
>
>
> }
>
>
> /**
> * For application use
> *
> * Call the application as:
> * Encrypt datafile keyfile destination
> *
> */
> public static void main(String[] args)
> {
> /* Encrypt a file using the public key */
> if (args.length != 3)
> {
> System.out.println("Usage: Encrypt datafile keyfile destination");
> }
> else try
> {
> Encrypt crypter = new Encrypt();
> crypter.loadKey( new FileInputStream(args[1]) );
> crypter.loadData( new FileInputStream(args[0]) );
> crypter.encrypt();
> crypter.saveData( new FileOutputStream(args[2]) );
> }
> catch (Exception e)
> {
> System.err.println("Caught exception " + e.toString());
> }
> }
>
> }
>
>
> ------------------
> Fil3: Decrypt.java
> ------------------
>
> import java.io.*;
> import java.security.*;
> import java.security.spec.*;
> import javax.crypto.*;
> import au.net.aba.crypto.provider.*;
>
> /**
> * Decrypt is used for decrypting files encrypted with Encrypt.
> * It can be used as a standalone application, or as a class from other
> applications.
> *
> * A typical usage-pattern is as follows:
> * 1) construct a Decrypt object
> * 2) use loadKey to load the private decryption key
> * 3) use loadCipher to load the encrypted data
> * 4) use decrypt to decrypt the data
> * 5) use saveData to save the decrypted (plaintext) data
> *
> *
> * @author Peter Lind
> * @version 1.0 - 15. august 2000
> */
> public class Decrypt
> {
> private PrivateKey privateKey; // the key for decryption
> private byte[] cipherText; // the encrypted data
> private byte[] plainText; // the decrypted data
>
>
> /**
> * Default constructor.
> *
> */
> public Decrypt( )
> {
> Security.addProvider(new ABAProvider());
> }
>
> /**
> * Loads the encoded key from a file and creates a privateKey object.
> *
> */
> public void loadKey( FileInputStream keyFile ) throws IOException,
> InvalidKeySpecException
> {
> // read the private key from file
> byte[] encodedKey = new byte[keyFile.available()];
> keyFile.read(encodedKey);
> keyFile.close();
>
> PKCS8EncodedKeySpec codedKey = new PKCS8EncodedKeySpec( encodedKey );
> try
> {
> KeyFactory keyfactory = KeyFactory.getInstance("RSA");
> privateKey = keyfactory.generatePrivate( codedKey );
> }
> catch ( java.security.NoSuchAlgorithmException nsaEx )
> {
> System.out.println("Internal Error - NSA RSA decrypt - loadkey ");
> }
> // now the privateKey contains a real private key !
> }
>
>
>
> /**
> * Loads an encrypted file as a bytestream, and turns it into a cipher
> object.
> *
> */
> public void loadCipher( FileInputStream cipherFile) throws IOException
> {
> cipherText = new byte[cipherFile.available()];
> cipherFile.read(cipherText);
> cipherFile.close();
> }
>
> public void setCipher( byte[] cipherbytes)
> {
> cipherText = cipherbytes;
> }
>
>
> public byte[] getData( )
> {
> return plainText;
> }
>
>
> /**
> * Saves the decrypted plaintext bytestream to a file.
> *
> */
> public void saveData( File plainFile ) throws IOException
> {
> saveData( new FileOutputStream( plainFile ));
> }
>
>
> public void saveData( FileOutputStream plainFile ) throws IOException
> {
> plainFile.write(plainText);
> plainFile.close();
> }
>
>
> /**
> * Decrypts the loaded data with the loaded key.
> *
> */
> public void decrypt() throws InvalidKeyException,
> IllegalBlockSizeException, BadPaddingException
> {
> // Setup cipher object
> try
> {
> Cipher coding = Cipher.getInstance("RSA/ECB/PKCS1Padding");
>
> // decrypt cipher with the private key
> coding.init(Cipher.DECRYPT_MODE, privateKey);
>
> plainText = coding.doFinal( cipherText );
> }
> catch ( java.security.NoSuchAlgorithmException nsaEx )
> {
> System.out.println("Internal Error - NSA decrypt ");
> }
> catch ( javax.crypto.NoSuchPaddingException nspEx )
> {
> System.out.println("Internal Error - No Such Padding decrypt ");
> }
> }
>
>
>
>
> /**
> * For application use.
> *
> * Call the application as:
> * Decrypt datafile keyfile destination
> *
> */
> public static void main(String[] args)
> {
> /* Decrypt a file using the private key */
> if (args.length != 3)
> {
> System.out.println("Usage: Decrypt datafile keyfile destination");
> }
> else try
> {
> Decrypt decrypter = new Decrypt();
> decrypter.loadKey( new FileInputStream(args[1]) );
> decrypter.loadCipher( new FileInputStream(args[0]) );
> decrypter.decrypt();
> decrypter.saveData( new FileOutputStream(args[2]) );
> }
> catch (Exception e)
> {
> System.err.println("Caught exception " + e.toString());
> }
> }
>
> }
>
>
>