位加密解密算法即將明文信息轉化為二進制數據,然后對這些二進制位進行加密便得到密文。位加密算法依托於計算機的強大的位處理能力,在實際應用中非常流行。現代密碼學中的很多加密、解密算法方案都依賴於位加密、解密思路,例如,非常流行的序列密碼方案。
1. 位加密、解密算法
在java語言中,提供了6種位運算符,如下表所示。在密碼學中,可以根據需要來選擇合適的位運算符進行加密、解密。一般來說,使用異或運算要比較方便。
位運算 | 名稱 |
& | 按位與(AND) |
| | 按位或(OR) |
^ | 按位異或(XOR) |
~ | 取反(NOT) |
<< | 左移 |
>> | 右移 |
使用異或運算符進行加密、解密的一個好處是,在二進制運算中,如果將一個明文的二進制位與密鑰進行按位“異或”運算,將得到密文;將此密文與密鑰再次進行按位“異或”運算,又可以得到明文。這樣,只需編寫一個函數便可以同時完成加密和解密兩種運算。
可以根據此思路來編寫相應的位加密、解密算法,代碼示例如下:
/** * 位加密解密算法 * @param str 明文(密文) * @param n 密鑰 * @return 密文(明文) */ static char[] bitcode(char[] str, char n){ int len,i; char[] wen; len=str.length; wen = new char[len]; for(i=0;i<len;i++){ wen[i]=(char) (str[i]^n); } return wen; }
2. 位加密、解密算法實例
完整的程序代碼示例如下:
package com.cn.mimaxue; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; //位加密、解密算法 public class BitJiami { /** * 位加密解密算法 * @param str 明文(密文) * @param n 密鑰 * @return 密文(明文) */ static char[] bitcode(char[] str, char n){ int len,i; char[] wen; len=str.length; wen = new char[len]; for(i=0;i<len;i++){ wen[i]=(char) (str[i]^n); } return wen; } public static void main(String[] args) throws IOException { char[] str,miwen,jiemi; int i; char n; String go; System.out.println("位加密解密算法演示!"); Scanner input = new Scanner(System.in); do{ System.out.print("請輸入位加密解密算法的密鑰:"); n = input.next().charAt(0); System.out.print("請輸入明文:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String strtemp=br.readLine(); str=strtemp.toCharArray(); System.out.print("明文為:"); for(i=0;i<str.length;i++){ System.out.print(str[i]); } System.out.println(); miwen=bitcode(str,n); System.out.print("密文為:"); for(i=0;i<miwen.length;i++){ System.out.print(miwen[i]); } System.out.println(); jiemi=bitcode(miwen,n); System.out.print("解密為:"); for(i=0;i<jiemi.length;i++){ System.out.print(jiemi[i]); } System.out.println(); System.out.print("是否繼續(y/n):"); go = input.next(); }while(go.equalsIgnoreCase("y")); System.out.println("退出程序!"); } }
程序運行結果如下:
位加密解密算法演示! 請輸入位加密解密算法的密鑰:5 請輸入明文:Hello everyone! 明文為:Hello everyone! 密文為:}PYYZPCPGLZ[P 解密為:Hello everyone! 是否繼續(y/n):y 請輸入位加密解密算法的密鑰:9 請輸入明文:The big bang theory! 明文為:The big bang theory! 密文為:mQ\[P^[XW^MQ\VK@ 解密為:The big bang theory! 是否繼續(y/n):n 退出程序!