"Michael Andersen" <mander48@students.aabc.dk> wrote
> er der nogen der har et eksempel på kryptering, som de eventuelt vil dele?
> jeg har rodet med det i et stykke tid og kan ikke få det til at køre. Det
> jeg har brug for er kryptering med offentlige/private nøgler.
Hejsa
Jeg bøvlede for et års tid siden med præcis det samme, og fik det aldrig til
at virke med SUNs JCE.
Det gik derimod meget bedre med openJCE - det plejede at ligge på
www.openjce.org, men siden svarer slet ikke for mig - nogle andre ???
Jeg importerer au.net.aba.crypto.provider.*; som var navnet på den tidlige
version af openjce jeg brugte - jeg ved ikke om der findes en
nyere/bedre/anden.
Det lykkedes mig aldrig at få disse kodeeksempler til at køre med Suns JCE -
altid fik jeg no such algorithm.
Men her følger tre java-filer, en til at generere et nøglesæt, en til at
kryptere en fil, og en til at dekryptere...
Jeg synes selv de er usædvanlig godt dokumenterede, men sig til hvis der er
spørgsmål
mvh
Peter Lind
----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 generate to generate the keyset
* 3) use savePublic to save the public key to an encoded file
* 4) use savePrivate to save the private key to an encoded file
*
*
* @author Peter Lind
* @version 1.0 - 15. august 2000
*/
public class GenerateKeys
{
private PrivateKey privateKey;
private PublicKey publicKey;
private KeyPairGenerator keygenerator;
/**
* Default constructor
*
*/
public GenerateKeys( )
{
}
/**
* Generate a set of keys.
*
*/
public void generate() throws NoSuchAlgorithmException
{
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
keygenerator = new RSAKeyPairGenerator();
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 != 2)
{
System.out.println("Usage: Generatekeys publicfile privatefile");
}
else try
{
GenerateKeys generator = new GenerateKeys( );
generator.generate( );
generator.savePublic( new FileOutputStream(args[1]) );
generator.savePrivate( new FileOutputStream(args[2]) );
}
catch (Exception e)
{
System.err.println("Caught exception " + e.toString());
}
}
}
----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
");
}
}
/**
* 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());
}
}
}
----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());
}
}
}