Java CipherクラスDESアルゴリズム(暗号化と復号化)

5573 ワード

Java CipherクラスDESアルゴリズム(暗号化と復号化)
1.暗号解読クラス
import java.security.*;

import javax.crypto.*;

import java.io.*;

//     
public class CipherMessage {
    private String algorithm; //   , DES
    private Key key; //          
    private String plainText; //   

    KeyGenerator keyGenerator;
    Cipher cipher;

    //        
    CipherMessage(String alg, String msg) {
        algorithm = alg;
        plainText = msg;
    }

    //
    public byte[] CipherMsg() {
        byte[] cipherText = null;

        try {
            //   Cipher  
            cipher = Cipher.getInstance(algorithm);
            //        (plainText),    (cipherText)
            cipher.init(Cipher.ENCRYPT_MODE, key); //        (Cipher.ENCRYPT_MODE),key   
            cipherText = cipher.doFinal(plainText.getBytes()); //           
            // String str = new String(cipherText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cipherText;
    }

    //
    public String EncipherMsg(byte[] cipherText, Key k) {
        byte[] sourceText = null;

        try {
            cipher.init(Cipher.DECRYPT_MODE, k); //        ,key   
            sourceText = cipher.doFinal(cipherText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(sourceText);

    }

    //     
    public Key initKey() {
        try {
            //      key
            keyGenerator = KeyGenerator.getInstance(algorithm);
            keyGenerator.init(56); //   DES  ,       56 
            key = keyGenerator.generateKey(); //     
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return key;
    }

    

    //   Key     
    public Key getKey() {
        return key;
    }

    //   Key     
    public Key getKey(byte[] k) {
        try {
            key = cipher.unwrap(k, algorithm, Cipher.DECRYPT_MODE);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return key;
    }

    //        byte[]   
    public byte[] getBinaryKey(Key k) {
        byte[] bk = null;
        try {
            bk = cipher.wrap(k);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return bk;
    }
}

 
2.テスト
import java.security.*;

import javax.crypto.*;

import java.io.*;

public class TestMain {

    public static void main(String[] args) {
        String algorithm = "DES"; //       ,   DES,DESede,Blowfish
        String message = "Hello World.         "; //    DES  
        Key key;

        CipherMessage cm = new CipherMessage(algorithm, message);
        key = cm.initKey();
        byte[] msg = cm.CipherMsg();
        System.out.println("       :" + new String(msg));
        // System.out.println("   :"+new String(cm.getBinaryKey(key)));

        
        System.out.println(cm.getBinaryKey(key));
        System.out.println("     :" + cm.EncipherMsg(msg, key));

    }

}