您的位置:首页 > 编程语言 > Java开发

一个简单的加密解密程序

2013-02-19 00:00 881 查看
import java.util.Scanner;

/**
*简单的加密算法
*原理:按key值对明文逐字节循环移位
*加密右移,解密左移等距(实际采用右移补距的方法)
*
* @author gdhuangsha@hotmail.com
* @version 0.1
*/

public final class Encryption
{
/**
*操作标记
*ENCRYPT - 加密标记
*/
public static final int ENCRYPT = 1;
/**
*操作标记
*DECRYPT - 解密标记
*/
public static final int DECRYPT = -1;

/**
*字节加密方法
*@param msg byte,明文
*@param key byte,密钥
*@param method 使用类中静态常量操作标记 Encrytpion.ENCRYPT及
*Encryption.DECRYPT
*@return 返回密文字节
*/
public static byte encryption(byte msg, byte key, int method)
{
// key的预处理,处理结果0<=key&&key<8
key = (byte)(method * (key % 8));
key = (byte)(key >= 0 ? key : key + 8);

// msg的预处理,避免msg首位为1
int nMsg =  msg & 255;
// 移位掩码,tmp保存低位溢出信息
int mask = (int) Math.pow(2, key) - 1;
int tmp = nMsg & mask;

// 循环移位
nMsg >>= key;
tmp <<= (8 - key);	//低位溢出信息移至高位
nMsg |= tmp;
return (byte)(255 & nMsg); //取出低8位
}

/**
*重载方法,用于加密字节数组。
*特别说明:利用new String(byte[])方法将密文转换为String后,再使用
*其getBytes()方法转换为byte[]并译码,不能得出正确结果!
*@param msg byte[],明文字节数组
*@param key byte[],密钥字节数组
*@param method 操作方法
*@return 返回密文字节数组
*/
public static byte[] encryption(byte[] msg, byte[] key, int method)
{
byte[] nMsg = new byte[msg.length];
for (int i = 0; i < msg.length; i++) {
nMsg[i] = encryption(msg[i], key[i % key.length], method);
}

return nMsg;
}

/**
*重载方法,用于加密String
*@param msg String,明文字节数组
*@param key String,密钥字节数组
*@param method 操作方法
*@return 返回密文字节数组
*/

public static byte[] encryption(String msg, String key, int method)
{
if (msg == null) {
System.out.println("错误:明文为空");
System.exit(-1);
}
if (key == null) {
System.out.println("错误:密文为空");
System.exit(-1);
}
return encryption(msg.getBytes(),
key.getBytes(),
method);
}

/*简单测试
*/
public static void main(String[] args)
{
System.out.print("请输入明文:");
Scanner sc = new Scanner(System.in);
String plaintext = sc.nextLine();

System.out.print("请输入密钥:");
String key = sc.nextLine();

byte[] bMsg = plaintext.getBytes();
byte[] bKey = key.getBytes();
byte[] bCipher = encryption(bMsg, bKey, ENCRYPT);

System.out.println("密文:" + new String(bCipher));

byte[] bTranslate = encryption(bCipher, bKey, DECRYPT);
System.out.println("译文:" + new String(bTranslate));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java基础 加密解密
相关文章推荐