Курсовая работа: Анализ предметной области
6. D.Esposito, “Supporting CryptoAPI in Real-World Applications”, MSDN, 1997.
7. http://java.org
8. S.K.Parmar, “An introduction to security”, Fred Cohen &Associates, 2000.
9. R.L/Rivest, A.Shamir and L.Adleman, “A method for obtaining digital signatures and public key cryptosystems”. Commun. ACM, vol.21, p. 120-126, 1978.
10. W.Diffie and M.E.Hellman, “New directions in cryptograpgy”, IEEE Trans.Inf.Theory, vol.IT-22, N6, p.644-654, Nov. 1976.
11. A.Menezes, P.van Oorschot, S.Vanstone, “Handbook of applied cryptography”, CRC Press, 1996.
Код класса my_java_sec
public class my_java_sec {
@SuppressWarnings("deprecation")
public static void main(String[] args){
// TODO Auto-generated method stub
FInterfaceForm fif = new FInterfaceForm();
fif.show();
}
}
Приложение Б
Код класса coding_files
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class CodingFiles {
Cipher ecipher;
Cipher dcipher;
public CodingFiles() {
// TODO Auto-generated constructor stub
}
public SecretKey initCoding()
{
try{
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
return key;
}
catch(Exception e)
{
}
return null;
}
public void iniCoding(SecretKey key)
{
try{
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
catch(Exception e)
{
}
}
public boolean fileEncode(String sourse,String result)
{
try{
FileInputStream inFile = new FileInputStream(sourse);
int bytesAvailable = inFile.available();
byte[] bytesReaded = new byte[bytesAvailable];
inFile.read(bytesReaded,0,bytesAvailable);
inFile.close();
byte[] br_enc = ecipher.doFinal(bytesReaded);
FileOutputStream outFile = new FileOutputStream(result);
outFile.write(br_enc);
outFile.close();
return true;
}
catch(Exception e)
{}
return false;
}
public boolean fileDecode(String sourse,String result)
{
try{
FileInputStream enc_inFile = new FileInputStream(sourse);
int enc_bytesAvailable = enc_inFile.available();
byte[] enc_bytesReaded = new byte[enc_bytesAvailable];
enc_inFile.read(enc_bytesReaded,0,enc_bytesAvailable);
enc_inFile.close();
byte[] br_dec =dcipher.doFinal(enc_bytesReaded);
FileOutputStream dec_outFile = new FileOutputStream(result);
dec_outFile.write(br_dec);
dec_outFile.close();
return true;
}
catch(Exception e)
{}
return false;
}
}
Приложение В
Код класса DigitalSignature
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
public class DigitalSignature {
public static void saveToFile (byte[] info, String filename) {
try {
FileOutputStream fos = new FileOutputStream(filename);
fos.write(info);
fos.close();
}
catch (Exception e){}
}
public static byte[] readFromFile (String fileName) {
byte[] info;
try {
FileInputStream fis = new FileInputStream(fileName);
info = new byte[fis.available()];
fis.read(info);
fis.close();
}
catch (Exception e) {info = new byte[0];}
return(info);
}
public static boolean CreateDigitalSignatureForFile(String puth)
{
try
{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");
dsa.initSign(priv);
FileInputStream fis = new FileInputStream(puth);
BufferedInputStream bufin = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int len;
while (bufin.available() != 0)
{
len = bufin.read(buffer);
dsa.update(buffer, 0, len);
}
bufin.close();
byte[] realSig = dsa.sign();
saveToFile (realSig,puth+".sig");
byte[] key = pub.getEncoded();
saveToFile (key,puth+".pubkey");
//byte[] priv_key = priv.getEncoded();
//saveToFile (priv_key,"privkey_"+puth);
return true;
}
catch (Exception e){}
return false;
}
public static boolean TestedByDigitalSignature(String puth, String sign_puth, String pubkey_puth){
try{
byte[] encKey = readFromFile(pubkey_puth);
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
byte[] sigToVerify = readFromFile(sign_puth);
Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
sig.initVerify(pubKey);
FileInputStream datafis = new FileInputStream(puth);
BufferedInputStream bufin = new BufferedInputStream(datafis);
byte[] buffer = new byte[1024];
int len;
while (bufin.available() != 0)
{
len = bufin.read(buffer);
sig.update(buffer, 0, len);
}
bufin.close();
boolean verifies = sig.verify(sigToVerify);
return verifies;
}
catch(Exception e){}
return false;
}
}
Приложение Г
Код класса FInterfaceForm
import java.awt.Button;
import java.awt.Event;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.crypto.SecretKey;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class FInterfaceForm extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
Button bt_enc = new Button("Закодировать файл");
Button bt_dec = new Button("Расшифровать файл");
Button bt_dsig = new Button("Подписать файл");
Button bt_testdsig = new Button("Проверить цифровую подпись");
public FInterfaceForm() {
// TODO Auto-generated constructor stub
this.setLayout(null);
this.setBounds(200, 200, 420, 90);
this.setTitle("Java sercurity");
bt_enc.setBounds(0, 0, 200, 25);
bt_dec.setBounds(200, 0, 200, 25);
bt_dsig.setBounds(0, 25, 200, 25);
bt_testdsig.setBounds(200, 25, 200, 25);
this.add(bt_enc);
this.add(bt_dec);
this.add(bt_dsig);
this.add(bt_testdsig);
}
@SuppressWarnings("deprecation")
@Override
public boolean action(Event evt, Object arg1) {
// TODO Auto-generated method stub
if(evt.target instanceof Button)
{
if(evt.target.equals(bt_enc))
{
try{
JFileChooser jfc = new JFileChooser();
jfc.setDialogTitle("Выберите файл для кодирования");
if( jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
JFileChooser jfc_s = new JFileChooser();
jfc_s.setDialogTitle("Как сохранить файл?");
if( jfc_s.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
JFileChooser jfc_s_key = new JFileChooser();
jfc_s_key.setDialogTitle("Как сохранить ключ?");
if( jfc_s_key.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
CodingFiles cf = new CodingFiles();
SecretKey sk = cf.initCoding();
FileOutputStream fos = new FileOutputStream((jfc_s_key.getSelectedFile()).getAbsolutePath());
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(sk);
oos.flush();
oos.close();
if(cf.fileEncode((jfc.getSelectedFile()).getAbsolutePath(), (jfc_s.getSelectedFile()).getAbsolutePath()))
JOptionPane.showMessageDialog(new JButton("Ok"), "Файл закодирован успешно!","Поздравляем!", JOptionPane.WARNING_MESSAGE);
else
JOptionPane.showMessageDialog(new JButton("Ok"), "Произошла ошибка при кодировании файла!","Что-то не так!", JOptionPane.WARNING_MESSAGE);
}
}
}
}catch(Exception e){}
}
if(evt.target.equals(bt_dec))
{
try{
JFileChooser jfc = new JFileChooser();
jfc.setDialogTitle("Выберите файл для расшифровки.");
if( jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
JFileChooser jfc_o = new JFileChooser();
jfc_o.setDialogTitle("Выбирете ключ для расшифровки этого файла.");
if( jfc_o.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
JFileChooser jfc_s = new JFileChooser();
jfc_s.setDialogTitle("Как сохранить расшифрованый файл?");
if( jfc_s.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
CodingFiles cf = new CodingFiles();
FileInputStream fis = new FileInputStream((jfc_o.getSelectedFile()).getAbsolutePath());
ObjectInputStream oin = new ObjectInputStream(fis);
SecretKey ts = (SecretKey) oin.readObject();
cf.iniCoding(ts);
if(cf.fileDecode((jfc.getSelectedFile()).getAbsolutePath(), (jfc_s.getSelectedFile()).getAbsolutePath()))
{
JOptionPane.showMessageDialog(new JButton("Ok"), "Файл расшифрован успешно!","Поздравляем!", JOptionPane.WARNING_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(new JButton("Ok"), "Файл не расшифрован! Возможно не подходящий ключ.","Что-то нето!", JOptionPane.WARNING_MESSAGE);
}
oin.close();
}
}
}
}catch(Exception e){}
}
if(evt.target.equals(bt_dsig))
{
try{
JFileChooser jfc = new JFileChooser();
jfc.setDialogTitle("Выберите файл для подписи.");
if( jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
if(DigitalSignature.CreateDigitalSignatureForFile((jfc.getSelectedFile()).getAbsolutePath()))
JOptionPane.showMessageDialog(new JButton("Ok"), "Файл подписан успешно! Вы можите найти файл с цифровой подписью и открытый ключ в каталоге с файлом.","Поздравляем!", JOptionPane.WARNING_MESSAGE);
else
JOptionPane.showMessageDialog(new JButton("Ok"), "Возник какойто эксепшен","Что-то пошло не так.!", JOptionPane.WARNING_MESSAGE);
}
}catch(Exception e){}
}
if(evt.target.equals(bt_testdsig))
{
try{
JFileChooser jfc = new JFileChooser();
jfc.setDialogTitle("Выберите файл для проверки подписи.");
if( jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
JFileChooser jfc_dg = new JFileChooser();
jfc_dg.setDialogTitle("Выберите файл с цифровой подписью.");
if( jfc_dg.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
JFileChooser jfc_key = new JFileChooser();
jfc_key.setDialogTitle("Выберите файл с открытым ключем.");
if( jfc_key.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
if(DigitalSignature.TestedByDigitalSignature((jfc.getSelectedFile()).getAbsolutePath(), (jfc_dg.getSelectedFile()).getAbsolutePath(), (jfc_key.getSelectedFile()).getAbsolutePath()))
JOptionPane.showMessageDialog(new JButton("Ok"), "Этот файл полностью соответствует этой цифровой подписи.","Поздравляем!", JOptionPane.WARNING_MESSAGE);
else
JOptionPane.showMessageDialog(new JButton("Ok"), "Этот файл либо небыл подписан этой подписью либо несанкционировано исправлен","Danger!!!", JOptionPane.WARNING_MESSAGE);
}
}
}
}catch(Exception e){}
}
}
return super.action(evt, arg1);
}
}