testblowfish.java

来自「Encrypt your stream data/file by JAVA」· Java 代码 · 共 35 行

JAVA
35
字号
package Crypto;

/**How to use the Blowfish algorithm to encrypt 64-bit blocks with a constant key */

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;

public class TestBlowfish {

static public void main (String args[]) throws Exception {
   byte[] key = {0x11,0x22,0x33,0x44};
   byte[] plainData = {0x55,(byte)0xaa,0x12,0x34,0x56,0x78,(byte)0x9a,(byte)0xbc};
   byte[] encryptedData = new byte[8];
   encrypt (plainData,encryptedData,key);
   byte[] decryptedData = new byte[8];
   decrypt (encryptedData,decryptedData,key);
   if (!Arrays.equals(plainData,decryptedData)) throw new Exception ("Decrypted data not equal.");
   System.out.println ("ok"); }

private static void encrypt (byte[] input, byte[] output, byte[] key) throws Exception {
   crypt (Cipher.ENCRYPT_MODE,input,output,key); }

private static void decrypt (byte[] input, byte[] output, byte[] key) throws Exception {
   crypt (Cipher.DECRYPT_MODE,input,output,key); }

private static void crypt (int opmode, byte[] input, byte[] output, byte[] key) throws Exception {
   Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding");
   SecretKeySpec keySpec = new SecretKeySpec(key,"Blowfish");
   cipher.init (opmode, keySpec);
   cipher.doFinal (input,0,input.length,output); }

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?