Java: 如何加密解密 How to encrypt and decrypt

Edit Time: 2006/12/12

By: JonsenElizee

E-mail: JonsenElizee@163.com

####################################################################################

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import java.io.*;
import java.util.Arrays;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.SecretKeyFactory;

public class EncryptionTest
{
    public static void main(String[] args)
    {
        EncryptionTest.simpleCryption();
        EncryptionTest.cryptPassword();
    }

    public static void simpleCryption()
    {

        try
        {
            //DES: Data Encryption Standard
            KeyGenerator keygen = KeyGenerator.getInstance("DES");
            SecretKey desKey = keygen.generateKey();

            Cipher desCipher;
            // Create the cipher
            //ECB: Electronic Codebook
            //PKCS5Padding: PKCS #5-style padding
            desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

            // Initialize the cipher for encryption
            desCipher.init(Cipher.ENCRYPT_MODE, desKey);
            // Our cleartext
            byte[] cleartext = "This is just an example".getBytes();
            // Encrypt the cleartext
            byte[] ciphertext = desCipher.doFinal(cleartext);
            // Initialize the same cipher for decryption
            desCipher.init(Cipher.DECRYPT_MODE, desKey);
            // Decrypt the ciphertext
            byte[] cleartext1 = desCipher.doFinal(ciphertext);

            System.out.println(new String(cleartext));   //outcome: This is just an example
            System.out.println(new String(ciphertext)); //outcome: ?(饖1e黡j3i爰滊?0府
            System.out.println(new String(cleartext1)); //outcome: This is just an example
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public static void cryptPassword()
    {
        try
        {
            PBEKeySpec pbeKeySpec;
            PBEParameterSpec pbeParamSpec;
            SecretKeyFactory keyFac;
            // Salt
            byte[] salt =
                          {(byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
                          (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99};
            // Iteration count
            int count = 20;
            // Create PBE parameter set
            pbeParamSpec = new PBEParameterSpec(salt, count);
            // Prompt user for encryption password.
            // Collect user password as char array (using the
            // "readPasswd" method from above), and convert
            // it into a SecretKey object, using a PBE key
            // factory.
            System.out.print("Enter encryption password:  ");
            System.out.flush();
            //Constructor that takes a password
            pbeKeySpec = new PBEKeySpec(readPassword(System.in));
            keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
            // Create PBE Cipher
            Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
            // Initialize PBE Cipher with key and parameters
            pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
            // Our cleartext
            byte[] cleartext = "This is another example".getBytes();
            // Encrypt the cleartext   
            byte[] ciphertext = pbeCipher.doFinal(cleartext);
            System.out.println("encrypted string: " + new String(ciphertext));
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    /*
     Using Password-Based Encryption
     In this example, we prompt the user for a password from which we derive an
     encryption key.
     It would seem logical to collect and store the password in an object of type
     java.lang.String. However, here's the caveat: Objects of type String are
     immutable, i.e., there are no methods defined that allow you to change
     (overwrite) or zero out the contents of a String after usage. This feature
     makes String objects unsuitable for storing security sensitive information
     such as user passwords. You should always collect and store security sensitive
     information in a char array instead.
     For that reason, the javax.crypto.spec.PBEKeySpec class takes (and returns) a
     password as a char array.

     The following method is an example of how to collect a user password as a char
     array:
     */
    //Reads user password from given input stream.
    public static char[] readPassword(InputStream inputStream) throws IOException
    {
        char[] lineBuffer;
        lineBuffer = new char[128];
        int offset = 0;
        int aChar;

        while (true)
        {
            switch (aChar = inputStream.read())
            {
                case -1:
                case '/n':
                    break;
                case '/r':
                    int tempChar = inputStream.read();
                    if ((tempChar != '/n') && (tempChar != -1))
                    {
                        if (!(inputStream instanceof PushbackInputStream))
                        {
                            inputStream = new PushbackInputStream(inputStream);
                        }
                        //pushes char back to re-read it
                        ((PushbackInputStream)inputStream).unread(tempChar);
                    }
                    else
                    {
                        break;
                    }
                default:
                    lineBuffer[offset++] = (char)aChar;
                    if (offset == 127)
                    {
                        //extends the length of the buffer
                        char[] tempCharArray = new char[lineBuffer.length + 128];
                        Arrays.fill(tempCharArray, ' ');
                        System.arraycopy(lineBuffer, 0, tempCharArray, 0, lineBuffer.length);
                        lineBuffer = tempCharArray;
                        offset = 0;
                    }
                    break;
            }
            if (new String(lineBuffer).trim().length() == 0)
            {
                return null;
            }
            else
            {
                return new String(lineBuffer).trim().toCharArray();
            }
        }
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值