当前位置:首页 » 编程语言 » java简单加密

java简单加密

发布时间: 2023-08-18 12:51:27

‘壹’ 用java设计一个简单的加密、解密算法,用该算法来实现对数据的加密、解密

简单的?

用异或就可以了..!

importjava.util.Scanner;

publicclass加密
{
privatestaticScannersc=newScanner(System.in);
publicstaticvoidmain(String[]Args)
{
System.out.println(" ================字符串加密演示===================== ");
init();
}
//初始化!
privatestaticvoidinit()
{
for(;;)
{
char[]arr=input();
jiaMi(arr,20140908);
jiaMi(20140908,arr);
}

}
//键盘录取!
privatestaticchar[]input()
{
Strings=sc.nextLine();
inta=s.length();
char[]arr=newchar[a];
//char[]arr=s.toCharArray();
for(inti=0;i<s.length();i++)
{
arr[i]=s.charAt(i);
}
returnarr;
}
//加密!!
privatestaticvoidjiaMi(char[]arr,inta)
{
for(inti=0;i<arr.length;i++)
{
arr[i]=((char)(arr[i]^a));
}
System.out.println("加密完成!");
print(arr);
}
//解密!!
privatestaticvoidjiaMi(inta,char[]arr)
{
for(inti=0;i<arr.length;i++)
{
arr[i]=((char)(arr[i]^a));
}
System.out.println("解密完成");
print(arr);
}
//打印!!
privatestaticvoidprint(char[]arr)
{
for(inti=0;i<arr.length;i++)
{
System.out.print(arr[i]);
}
System.out.println(" ========================= ");
}
}

‘贰’ 漫谈Java加密技术(二)

接下来我们介绍对称加密算法 最常用的莫过于DES数据加密算法

DES

DES Data Encryption Standard 即数据加密算法 是IBM公司于 年研究成功并公开发表的 DES算法的入口参数有三个 Key Data Mode 其中Key为 个字节共 位 是DES算法的工作密钥 Data也为 个字节 位 是要被加密或被解密的数据 Mode为DES的工作方式 有两种 加密或解密

DES算法把 位的明文输入块变为 位的密文输出块 它所使用的密钥也是 位

通过java代码实现如下

importjava security Key;importjava security SecureRandom;importjavax crypto Cipher;importjavax crypto KeyGenerator;importjavax crypto SecretKey;importjavax crypto SecretKeyFactory;importjavax crypto spec DESKeySpec;/***//***DES安全编码组件authorby;**<pre>*支持DES DESede(TripleDES 就是 DES) AES Blowfish RC RC (ARCFOUR)*DESkeysizemustbeequalto *DESede(TripleDES)keysizemustbeequalto or *AESkeysizemustbeequalto or but and bitsmaynotbeavailable* andcanonlyrangefrom to (inclusive)*RC keysizemustbebeeen and bits*RC (ARCFOUR)keysizemustbebeeen and bits*具体内容需要关注JDKDocument&///docs/technotes/guides/security/l*</pre>**@author梁栋*@version *@since */{/***//***ALGORITHM算法<br>*可替换为以下任意一种算法 同时key值的size相应改变 **<pre>*DESkeysizemustbeequalto *DESede(TripleDES)keysizemustbeequalto or *AESkeysizemustbeequalto or but and bitsmaynotbeavailable* andcanonlyrangefrom to (inclusive)*RC keysizemustbebeeen and bits*RC (ARCFOUR)keysizemustbebeeen and bits*</pre>**在KeytoKey(byte[]key)方法中使用下述代码*<code>SecretKeysecretKey=newSecretKeySpec(key ALGORITHM);</code>替换*<code>*DESKeySpecdks=newDESKeySpec(key);*SecretKeyFactorykeyFactory=SecretKeyFactory getInstance(ALGORITHM);*SecretKeysecretKey=keyFactory generateSecret(dks);*</code>*/= DES ;/***//***转换密钥<br>**@paramkey*@return*@throwsException*/privatestaticKeytoKey(byte[]key)throwsException{DESKeySpecdks=newDESKeySpec(key);SecretKeyFactorykeyFactory=SecretKeyFactory getInstance(ALGORITHM);SecretKeysecretKey=keyFactory generateSecret(dks);//当使用其他对称加密算法时 如AES Blowfish等算法时 用下述代码替换上述三行代码//SecretKeysecretKey=newSecretKeySpec(key ALGORITHM);returnsecretKey;}/***//***解密**@paramdata*@paramkey*@return*@throwsException*/publicstaticbyte[]decrypt(byte[]data Stringkey)throwsException{Keyk=toKey(decryptBASE (key));Ciphercipher=Cipher getInstance(ALGORITHM);cipher init(Cipher DECRYPT_MODE k);returncipher doFinal(data);}/***//***加密**@paramdata*@paramkey*@return*@throwsException*/publicstaticbyte[]encrypt(byte[]data Stringkey)throwsException{Keyk=toKey(decryptBASE (key));Ciphercipher=Cipher getInstance(ALGORITHM);cipher init(Cipher ENCRYPT_MODE k);returncipher doFinal(data);}/***//***生成密钥**@return*@throwsException*/publicstaticStringinitKey()throwsException{returninitKey(null);}/***//***生成密钥**@paramseed*@return*@throwsException*/publicstaticStringinitKey(Stringseed)throwsException{SecureRandomsecureRandom=null;if(seed!=null){secureRandom=newSecureRandom(decryptBASE (seed));}else{secureRandom=newSecureRandom();}KeyGeneratorkg=KeyGenerator getInstance(ALGORITHM);kg init(secureRandom);SecretKeysecretKey=kg generateKey();returnencryptBASE (secretKey getEncoded());}}

延续上一个类的实现 我们通过MD 以及SHA对字符串加密生成密钥 这是比较常见的密钥生成方式

再给出一个测试类

importstatic junit Assert *;import junit Test;/***//****@authorby;;*@version *@since */publicclassDESCoderTest{@Testpublicvoidtest()throwsException{StringinputStr= DES ;Stringkey=DESCoder initKey();System err println( 原文: +inputStr);System err println( 密钥: +key);byte[]inputData=inputStr getBytes();inputData=DESCoder encrypt(inputData key);System err println( 加密后: +DESCoder encryptBASE (inputData));byte[]outputData=DESCoder decrypt(inputData key);StringoutputStr=newString(outputData);System err println( 解密后: +outputStr);assertEquals(inputStr outputStr);}}

得到的输出内容如下

原文 DES

密钥 f wEtRrV q =

加密后 C qe oNIzRY=

解密后 DES

由控制台得到的输出 我们能够比对加密 解密后结果一致 这是一种简单的加密解密方式 只有一个密钥

其实DES有很多同胞兄弟 如DESede(TripleDES) AES Blowfish RC RC (ARCFOUR) 这里就不过多阐述了 大同小异 只要换掉ALGORITHM换成对应的值 同时做一个代码替换SecretKey secretKey = new SecretKeySpec(key ALGORITHM) 就可以了 此外就是密钥长度不同了

/**

lishixin/Article/program/Java/gj/201311/27624

‘叁’ 如何使用java对密码加密 加密方式aes

Java有相关的实现类:具体原理如下
对于任意长度的明文,AES首先对其进行分组,每组的长度为128位。分组之后将分别对每个128位的明文分组进行加密。
对于每个128位长度的明文分组的加密过程如下:
(1)将128位AES明文分组放入状态矩阵中。
(2)AddRoundKey变换:对状态矩阵进行AddRoundKey变换,与膨胀后的密钥进行异或操作(密钥膨胀将在实验原理七中详细讨论)。
(3)10轮循环:AES对状态矩阵进行了10轮类似的子加密过程。前9轮子加密过程中,每一轮子加密过程包括4种不同的变换,而最后一轮只有3种变换,前9轮的子加密步骤如下:
● SubBytes变换:SubBytes变换是一个对状态矩阵非线性的变换;
● ShiftRows变换:ShiftRows变换对状态矩阵的行进行循环移位;
● MixColumns变换:MixColumns变换对状态矩阵的列进行变换;
● AddRoundKey变换:AddRoundKey变换对状态矩阵和膨胀后的密钥进行异或操作。
最后一轮的子加密步骤如下:
● SubBytes变换:SubBytes变换是一个对状态矩阵非线性的变换;
● ShiftRows变换:ShiftRows变换对状态矩阵的行进行循环移位;
● AddRoundKey变换:AddRoundKey变换对状态矩阵和膨胀后的密钥进行异或操作;
(4)经过10轮循环的状态矩阵中的内容就是加密后的密文。
AES的加密算法的伪代码如下。

在AES算法中,AddRoundKey变换需要使用膨胀后的密钥,原始的128位密钥经过膨胀会产生44个字(每个字为32位)的膨胀后的密钥,这44个字的膨胀后的密钥供11次AddRoundKey变换使用,一次AddRoundKey使用4个字(128位)的膨胀后的密钥。
三.AES的分组过程
对于任意长度的明文,AES首先对其进行分组,分组的方法与DES相同,即对长度不足的明文分组后面补充0即可,只是每一组的长度为128位。
AES的密钥长度有128比特,192比特和256比特三种标准,其他长度的密钥并没有列入到AES联邦标准中,在下面的介绍中,我们将以128位密钥为例。
四.状态矩阵
状态矩阵是一个4行、4列的字节矩阵,所谓字节矩阵就是指矩阵中的每个元素都是一个1字节长度的数据。我们将状态矩阵记为State,State中的元素记为Sij,表示状态矩阵中第i行第j列的元素。128比特的明文分组按字节分成16块,第一块记为“块0”,第二块记为“块1”,依此类推,最后一块记为“块15”,然后将这16块明文数据放入到状态矩阵中,将这16块明文数据放入到状态矩阵中的方法如图2-2-1所示。

块0

块4

块8

块12

块1

块5

块9

块13

块2

块6

块10

块14

块3

块7

块11

块15

图2-2-1 将明文块放入状态矩阵中
五.AddRoundKey变换
状态矩阵生成以后,首先要进行AddRoundKey变换,AddRoundKey变换将状态矩阵与膨胀后的密钥进行按位异或运算,如下所示。

其中,c表示列数,数组W为膨胀后的密钥,round为加密轮数,Nb为状态矩阵的列数。
它的过程如图2-2-2所示。

图2-2-2 AES算法AddRoundKey变换
六.10轮循环
经过AddRoundKey的状态矩阵要继续进行10轮类似的子加密过程。前9轮子加密过程中,每一轮要经过4种不同的变换,即SubBytes变换、ShiftRows变换、MixColumns变换和AddRoundKey变换,而最后一轮只有3种变换,即SubBytes变换、ShiftRows变换和AddRoundKey变换。AddRoundKey变换已经讨论过,下面分别讨论余下的三种变换。
1.SubBytes变换
SubBytes是一个独立作用于状态字节的非线性变换,它由以下两个步骤组成:
(1)在GF(28)域,求乘法的逆运算,即对于α∈GF(28)求β∈GF(28),使αβ =βα = 1mod(x8 + x4 + x3 + x + 1)。
(2)在GF(28)域做变换,变换使用矩阵乘法,如下所示:

由于所有的运算都在GF(28)域上进行,所以最后的结果都在GF(28)上。若g∈GF(28)是GF(28)的本原元素,则对于α∈GF(28),α≠0,则存在
β ∈ GF(28),使得:
β = gαmod(x8 + x4 + x3 + x + 1)
由于g255 = 1mod(x8 + x4 + x3 + x + 1)
所以g255-α = β-1mod(x8 + x4 + x3 + x + 1)
根据SubBytes变换算法,可以得出SubBytes的置换表,如表2-2-1所示,这个表也叫做AES的S盒。该表的使用方法如下:状态矩阵中每个元素都要经过该表替换,每个元素为8比特,前4比特决定了行号,后4比特决定了列号,例如求SubBytes(0C)查表的0行C列得FE。
表2-2-1 AES的SubBytes置换表

它的变换过程如图2-2-3所示。

图2-2-3 SubBytes变换
AES加密过程需要用到一些数学基础,其中包括GF(2)域上的多项式、GF(28)域上的多项式的计算和矩阵乘法运算等,有兴趣的同学请参考相关的数学书籍。
2.ShiftRows变换
ShiftRows变换比较简单,状态矩阵的第1行不发生改变,第2行循环左移1字节,第3行循环左移2字节,第4行循环左移3字节。ShiftRows变换的过程如图2-2-4所示。

图2-2-4 AES的ShiftRows变换
3.MixColumns变换
在MixColumns变换中,状态矩阵的列看作是域GF(28)的多项式,模(x4+1)乘以c(x)的结果:
c(x)=(03)x3+(01)x2+(01)x+(02)
这里(03)为十六进制表示,依此类推。c(x)与x4+1互质,故存在逆:
d(x)=(0B)x3+(0D)x2+(0G)x+(0E)使c(x)•d(x) = (D1)mod(x4+1)。
设有:

它的过程如图2-2-5所示。

图2-2-5 AES算法MixColumns变换
七.密钥膨胀
在AES算法中,AddRoundKey变换需要使用膨胀后的密钥,膨胀后的密钥记为子密钥,原始的128位密钥经过膨胀会产生44个字(每个字为32位)的子密钥,这44个字的子密钥供11次AddRoundKey变换使用,一次AddRoundKey使用4个字(128位)的膨胀后的密钥。
密钥膨胀算法是以字为基础的(一个字由4个字节组成,即32比特)。128比特的原始密钥经过膨胀后将产生44个字的子密钥,我们将这44个密钥保存在一个字数组中,记为W[44]。128比特的原始密钥分成16份,存放在一个字节的数组:Key[0],Key[1]……Key[15]中。
在密钥膨胀算法中,Rcon是一个10个字的数组,在数组中保存着算法定义的常数,分别为:
Rcon[0] = 0x01000000
Rcon[1] = 0x02000000
Rcon[2] = 0x04000000
Rcon[3] = 0x08000000
Rcon[4] = 0x10000000
Rcon[5] = 0x20000000
Rcon[6] = 0x40000000
Rcon[7] = 0x80000000
Rcon[8] = 0x1b000000
Rcon[9] = 0x36000000
另外,在密钥膨胀中包括其他两个操作RotWord和SubWord,下面对这两个操作做说明:
RotWord( B0,B1,B2,B3 )对4个字节B0,B1,B2,B3进行循环移位,即
RotWord( B0,B1,B2,B3 ) = ( B1,B2,B3,B0 )
SubWord( B0,B1,B2,B3 )对4个字节B0,B1,B2,B3使用AES的S盒,即
SubWord( B0,B1,B2,B3 ) = ( B’0,B’1,B’2,B’3 )
其中,B’i = SubBytes(Bi),i = 0,1,2,3。
密钥膨胀的算法如下:

八.解密过程
AES的加密和解密过程并不相同,首先密文按128位分组,分组方法和加密时的分组方法相同,然后进行轮变换。
AES的解密过程可以看成是加密过程的逆过程,它也由10轮循环组成,每一轮循环包括四个变换分别为InvShiftRows变换、InvSubBytes变换、InvMixColumns变换和AddRoundKey变换;
这个过程可以描述为如下代码片段所示:

九.InvShiftRows变换
InvShiftRows变换是ShiftRows变换的逆过程,十分简单,指定InvShiftRows的变换如下。
Sr,(c+shift(r,Nb))modNb= Sr,c for 0 < r< 4 and 0 ≤ c < Nb
图2-2-6演示了这个过程。

图2-2-6 AES算法InvShiftRows变换
十.InvSubBytes变换
InvSubBytes变换是SubBytes变换的逆变换,利用AES的S盒的逆作字节置换,表2-2-2为InvSubBytes变换的置换表。
表2-2-2 InvSubBytes置换表

十一.InvMixColumns变换
InvMixColumns变换与MixColumns变换类似,每列乘以d(x)
d(x) = (OB)x3 + (0D)x2 + (0G)x + (0E)
下列等式成立:
( (03)x3 + (01)x2 + (01)x + (02) )⊙d(x) = (01)
上面的内容可以描述为以下的矩阵乘法:

十二.AddRoundKey变换
AES解密过程的AddRoundKey变换与加密过程中的AddRoundKey变换一样,都是按位与子密钥做异或操作。解密过程的密钥膨胀算法也与加密的密钥膨胀算法相同。最后状态矩阵中的数据就是明文。

‘肆’ 可变MD5加密(Java实现)

可变在这里含义很简单 就是最终的加密结果是可变的 而非必需按标准MD 加密实现 Java类库security中的MessageDigest类就提供了MD 加密的支持 实现起来非常方便 为了实现更多效果 我们可以如下设计MD 工具类

Java代码

package ** ** util;

import java security MessageDigest;

/**

* 标准MD 加密方法 使用java类库的security包的MessageDigest类处理

* @author Sarin

*/

public class MD {

/**

* 获得MD 加密密码的方法

*/

public static String getMD ofStr(String origString) {

String origMD = null;

try {

MessageDigest md = MessageDigest getInstance( MD );

byte[] result = md digest(origString getBytes());

origMD = byteArray HexStr(result);

} catch (Exception e) {

e printStackTrace();

}

return origMD ;

}

/**

* 处理字节数组得到MD 密码的方法

*/

private static String byteArray HexStr(byte[] bs) {

StringBuffer *** = new StringBuffer();

for (byte b : bs) {

*** append(byte HexStr(b));

}

return *** toString();

}

/**

* 字节标准移位转十六进制方法

*/

private static String byte HexStr(byte b) {

String hexStr = null;

int n = b;

if (n < ) {

//若需要自定义加密 请修改这个移位算法即可

n = b & x F + ;

}

hexStr = Integer toHexString(n / ) + Integer toHexString(n % );

return hexStr toUpperCase();

}

/**

* 提供一个MD 多次加密方法

*/

public static String getMD ofStr(String origString int times) {

String md = getMD ofStr(origString);

for (int i = ; i < times ; i++) {

md = getMD ofStr(md );

}

return getMD ofStr(md );

}

/**

* 密码验证方法

*/

public static boolean verifyPassword(String inputStr String MD Code) {

return getMD ofStr(inputStr) equals(MD Code);

}

/**

* 重载一个多次加密时的密码验证方法

*/

public static boolean verifyPassword(String inputStr String MD Code int times) {

return getMD ofStr(inputStr times) equals(MD Code);

}

/**

* 提供一个测试的主函数

*/

public static void main(String[] args) {

System out println( : + getMD ofStr( ));

System out println( : + getMD ofStr( ));

System out println( sarin: + getMD ofStr( sarin ));

System out println( : + getMD ofStr( ));

}

}

可以看出实现的过程非常简单 因为由java类库提供了处理支持 但是要清楚的是这种方式产生的密码不是标准的MD 码 它需要进行移位处理才能得到标准MD 码 这个程序的关键之处也在这了 怎么可变?调整移位算法不就可变了么!不进行移位 也能够得到 位的密码 这就不是标准加密了 只要加密和验证过程使用相同的算法就可以了

MD 加密还是很安全的 像CMD 那些穷举破解的只是针对标准MD 加密的结果进行的 如果自定义移位算法后 它还有效么?可以说是无解的了 所以MD 非常安全可靠

为了更可变 还提供了多次加密的方法 可以在MD 基础之上继续MD 就是对 位的第一次加密结果再MD 恩 这样去破解?没有任何意义

这样在MIS系统中使用 安全可靠 欢迎交流 希望对使用者有用

我们最后看看由MD 加密算法实现的类 那是非常庞大的

Java代码

import java lang reflect *;

/**

* **********************************************

* md 类实现了RSA Data Security Inc 在提交给IETF

* 的RFC 中的MD message digest 算法

* ***********************************************

*/

public class MD {

/* 下面这些S S 实际上是一个 * 的矩阵 在原始的C实现中是用#define 实现的

这里把它们实现成为static final是表示了只读 切能在同一个进程空间内的多个

Instance间共享*/

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final byte[] PADDING = {

};

/* 下面的三个成员是MD 计算过程中用到的 个核心数据 在原始的C实现中

被定义到MD _CTX结构中

*/

private long[] state = new long[ ]; // state (ABCD)

private long[] count = new long[ ]; // number of bits molo ^ (l *** first)

private byte[] buffer = new byte[ ]; // input buffer

/* digestHexStr是MD 的唯一一个公共成员 是最新一次计算结果的

进制ASCII表示

*/

public String digestHexStr;

/* digest 是最新一次计算结果的 进制内部表示 表示 bit的MD 值

*/

private byte[] digest = new byte[ ];

/*

getMD ofStr是类MD 最主要的公共方法 入口参数是你想要进行MD 变换的字符串

返回的是变换完的结果 这个结果是从公共成员digestHexStr取得的.

*/

public String getMD ofStr(String inbuf) {

md Init();

md Update(inbuf getBytes() inbuf length());

md Final();

digestHexStr = ;

for (int i = ; i < ; i++) {

digestHexStr += byteHEX(digest[i]);

}

return digestHexStr;

}

// 这是MD 这个类的标准构造函数 JavaBean要求有一个public的并且没有参数的构造函数

public MD () {

md Init();

return;

}

/* md Init是一个初始化函数 初始化核心变量 装入标准的幻数 */

private void md Init() {

count[ ] = L;

count[ ] = L;

///* Load magic initialization constants

state[ ] = x L;

state[ ] = xefcdab L;

state[ ] = x badcfeL;

state[ ] = x L;

return;

}

/* F G H I 是 个基本的MD 函数 在原始的MD 的C实现中 由于它们是

简单的位运算 可能出于效率的考虑把它们实现成了宏 在java中 我们把它们

实现成了private方法 名字保持了原来C中的 */

private long F(long x long y long z) {

return (x & y) | ((~x) & z);

}

private long G(long x long y long z) {

return (x & z) | (y & (~z));

}

private long H(long x long y long z) {

return x ^ y ^ z;

}

private long I(long x long y long z) {

return y ^ (x | (~z));

}

/*

FF GG HH和II将调用F G H I进行近一步变换

FF GG HH and II transformations for rounds and

Rotation is separate from addition to prevent reputation

*/

private long FF(long a long b long c long d long x long s long ac) {

a += F(b c d) + x + ac;

a = ((int) a << s) | ((int) a >>> ( s));

a += b;

return a;

}

private long GG(long a long b long c long d long x long s long ac) {

a += G(b c d) + x + ac;

a = ((int) a << s) | ((int) a >>> ( s));

a += b;

return a;

}

private long HH(long a long b long c long d long x long s long ac) {

a += H(b c d) + x + ac;

a = ((int) a << s) | ((int) a >>> ( s));

a += b;

return a;

}

private long II(long a long b long c long d long x long s long ac) {

a += I(b c d) + x + ac;

a = ((int) a << s) | ((int) a >>> ( s));

a += b;

return a;

}

/*

md Update是MD 的主计算过程 inbuf是要变换的字节串 inputlen是长度 这个

函数由getMD ofStr调用 调用之前需要调用md init 因此把它设计成private的

*/

private void md Update(byte[] inbuf int inputLen) {

int i index partLen;

byte[] block = new byte[ ];

index = (int) (count[ ] >>> ) & x F;

// /* Update number of bits */

if ((count[ ] += (inputLen << )) < (inputLen << ))

count[ ]++;

count[ ] += (inputLen >>> );

partLen = index;

// Transform as many times as possible

if (inputLen >= partLen) {

md Memcpy(buffer inbuf index partLen);

md Transform(buffer);

for (i = partLen; i + < inputLen; i += ) {

md Memcpy(block inbuf i );

md Transform(block);

}

index = ;

} else

i = ;

///* Buffer remaining input */

md Memcpy(buffer inbuf index i inputLen i);

}

/*

md Final整理和填写输出结果

*/

private void md Final() {

byte[] bits = new byte[ ];

int index padLen;

///* Save number of bits */

Encode(bits count );

///* Pad out to mod

index = (int) (count[ ] >>> ) & x f;

padLen = (index < ) ? ( index) : ( index);

md Update(PADDING padLen);

///* Append length (before padding) */

md Update(bits );

///* Store state in digest */

Encode(digest state );

}

/* md Memcpy是一个内部使用的byte数组的块拷贝函数 从input的inpos开始把len长度的

字节拷贝到output的outpos位置开始

*/

private void md Memcpy(byte[] output byte[] input int outpos int inpos int len) {

int i;

for (i = ; i < len; i++)

output[outpos + i] = input[inpos + i];

}

/*

md Transform是MD 核心变换程序 有md Update调用 block是分块的原始字节

*/

private void md Transform(byte block[]) {

long a = state[ ] b = state[ ] c = state[ ] d = state[ ];

long[] x = new long[ ];

Decode(x block );

/* Round */

a = FF(a b c d x[ ] S xd aa L); /* */

d = FF(d a b c x[ ] S xe c b L); /* */

c = FF(c d a b x[ ] S x dbL); /* */

b = FF(b c d a x[ ] S xc bdceeeL); /* */

a = FF(a b c d x[ ] S xf c fafL); /* */

d = FF(d a b c x[ ] S x c aL); /* */

c = FF(c d a b x[ ] S xa L); /* */

b = FF(b c d a x[ ] S xfd L); /* */

a = FF(a b c d x[ ] S x d L); /* */

d = FF(d a b c x[ ] S x b f afL); /* */

c = FF(c d a b x[ ] S xffff bb L); /* */

b = FF(b c d a x[ ] S x cd beL); /* */

a = FF(a b c d x[ ] S x b L); /* */

d = FF(d a b c x[ ] S xfd L); /* */

c = FF(c d a b x[ ] S xa eL); /* */

b = FF(b c d a x[ ] S x b L); /* */

/* Round */

a = GG(a b c d x[ ] S xf e L); /* */

d = GG(d a b c x[ ] S xc b L); /* */

c = GG(c d a b x[ ] S x e a L); /* */

b = GG(b c d a x[ ] S xe b c aaL); /* */

a = GG(a b c d x[ ] S xd f dL); /* */

d = GG(d a b c x[ ] S x L); /* */

c = GG(c d a b x[ ] S xd a e L); /* */

b = GG(b c d a x[ ] S xe d fbc L); /* */

a = GG(a b c d x[ ] S x e cde L); /* */

d = GG(d a b c x[ ] S xc d L); /* */

c = GG(c d a b x[ ] S xf d d L); /* */

b = GG(b c d a x[ ] S x a edL); /* */

a = GG(a b c d x[ ] S xa e e L); /* */

d = GG(d a b c x[ ] S xfcefa f L); /* */

c = GG(c d a b x[ ] S x f d L); /* */

b = GG(b c d a x[ ] S x d a c aL); /* */

/* Round */

a = HH(a b c d x[ ] S xfffa L); /* */

d = HH(d a b c x[ ] S x f L); /* */

c = HH(c d a b x[ ] S x d d L); /* */

b = HH(b c d a x[ ] S xfde cL); /* */

a = HH(a b c d x[ ] S xa beea L); /* */

d = HH(d a b c x[ ] S x bdecfa L); /* */

c = HH(c d a b x[ ] S xf bb b L); /* */

b = HH(b c d a x[ ] S xbebfbc L); /* */

a = HH(a b c d x[ ] S x b ec L); /* */

d = HH(d a b c x[ ] S xeaa faL); /* */

c = HH(c d a b x[ ] S xd ef L); /* */

b = HH(b c d a x[ ] S x d L); /* */

a = HH(a b c d x[ ] S xd d d L); /* */

d = HH(d a b c x[ ] S xe db e L); /* */

c = HH(c d a b x[ ] S x fa cf L); /* */

b = HH(b c d a x[ ] S xc ac L); /* */

/* Round */

a = II(a b c d x[ ] S xf L); /* */

d = II(d a b c x[ ] S x aff L); /* */

c = II(c d a b x[ ] S xab a L); /* */

b = II(b c d a x[ ] S xfc a L); /* */

a = II(a b c d x[ ] S x b c L); /* */

d = II(d a b c x[ ] S x f ccc L); /* */

c = II(c d a b x[ ] S xffeff dL); /* */

b = II(b c d a x[ ] S x dd L); /* */

a = II(a b c d x[ ] S x fa e fL); /* */

d = II(d a b c x[ ] S xfe ce e L); /* */

c = II(c d a b x[ ] S xa L); /* */

b = II(b c d a x[ ] S x e a L); /* */

a = II(a b c d x[ ] S xf e L); /* */

d = II(d a b c x[ ] S xbd af L); /* */

c = II(c d a b x[ ] S x ad d bbL); /* */

b = II(b c d a x[ ] S xeb d L); /* */

state[ ] += a;

state[ ] += b;

state[ ] += c;

state[ ] += d;

}

/*Encode把long数组按顺序拆成byte数组 因为java的long类型是 bit的

只拆低 bit 以适应原始C实现的用途

*/

private void Encode(byte[] output long[] input int len) {

int i j;

for (i = j = ; j < len; i++ j += ) {

output[j] = (byte) (input[i] & xffL);

output[j + ] = (byte) ((input[i] >>> ) & xffL);

output[j + ] = (byte) ((input[i] >>> ) & xffL);

output[j + ] = (byte) ((input[i] >>> ) & xffL);

}

}

/*Decode把byte数组按顺序合成成long数组 因为java的long类型是 bit的

只合成低 bit 高 bit清零 以适应原始C实现的用途

*/

private void Decode(long[] output byte[] input int len) {

int i j;

for (i = j = ; j < len; i++ j += )

output[i] = b iu(input[j]) | (b iu(input[j + ]) << ) | (b iu(input[j + ]) << )

| (b iu(input[j + ]) << );

return;

}

/*

b iu是我写的一个把byte按照不考虑正负号的原则的"升位"程序 因为java没有unsigned运算

*/

public static long b iu(byte b) {

return b < ? b & x F + : b;

}

/*byteHEX() 用来把一个byte类型的数转换成十六进制的ASCII表示

因为java中的byte的toString无法实现这一点 我们又没有C语言中的

sprintf(outbuf % X ib)

*/

public static String byteHEX(byte ib) {

char[] Digit = { A B C D E F };

char[] ob = new char[ ];

ob[ ] = Digit[(ib >>> ) & X F];

ob[ ] = Digit[ib & X F];

String s = new String(ob);

return s;

}

public static void main(String args[]) {

MD m = new MD ();

if (Array getLength(args) == ) { //如果没有参数 执行标准的Test Suite

System out println( MD Test suite: );

System out println( MD ( ): + m getMD ofStr( ));

System out println( MD ( a ): + m getMD ofStr( a ));

System out println( MD ( abc ): + m getMD ofStr( abc ));

System out println( MD ( ): + m getMD ofStr( ));

System out println( MD ( ): + m getMD ofStr( ));

System out println( MD ( message digest ): + m getMD ofStr( message digest ));

System out println( MD ( abcdefghijklmnopqrstuvwxyz ): + m getMD ofStr( abcdefghijklmnopqrstuvwxyz ));

System out println( MD ( ):

+ m getMD ofStr( ));

} else

System out println( MD ( + args[ ] + )= + m getMD ofStr(args[ ]));

}

lishixin/Article/program/Java/hx/201311/26604

‘伍’ java密码加密与解密

以下两个类可以很方便的完成字符串的加密和解密

加密 CryptHelper encrypt(password)

解密 CrypHelper decrypt(password)

代码如下

CryptUtils java

[java]

package gdie lab crypt;

import java io IOException;

import javax crypto Cipher;

import javax crypto KeyGenerator;

import javax crypto SecretKey;

import apache xerces internal impl dv util Base ;

public class CryptUtils {

private static String Algorithm = DES ;

private static byte[] DEFAULT_KEY=new byte[] { };

private static String VALUE_ENCODING= UTF ;

/**

* 生成密钥

*

* @return byte[] 返回生成的密钥

* @throws exception

* 扔出异常

*/

public static byte[] getSecretKey() throws Exception {

KeyGenerator keygen = KeyGenerator getInstance(Algorithm)

SecretKey deskey = keygen generateKey()

// if (debug ) System out println ( 生成密钥 +byte hex (deskey getEncoded

// ()))

return deskey getEncoded()

}

/**

* 将指定的数据根据提供的密钥进行加密

*

* @param input

* 需要加密的数据

* @param key

* 密钥

* @return byte[] 加密后的数据

* @throws Exception

*/

public static byte[] encryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug )

// {

// System out println ( 加密前的二进串 +byte hex (input ))

// System out println ( 加密前的字符串 +new String (input ))

//

// }

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher ENCRYPT_MODE deskey)

byte[] cipherByte = c doFinal(input)

// if (debug ) System out println ( 加密后的二进串 +byte hex (cipherByte ))

return cipherByte;

}

public static byte[] encryptData(byte[] input) throws Exception {

return encryptData(input DEFAULT_KEY)

}

/**

* 将给定的已加密的数据通过指定的密钥进行解密

*

* @param input

* 待解密的数据

* @param key

* 密钥

* @return byte[] 解密后的数据

* @throws Exception

*/

public static byte[] decryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug ) System out println ( 解密前的信息 +byte hex (input ))

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher DECRYPT_MODE deskey)

byte[] clearByte = c doFinal(input)

// if (debug )

// {

// System out println ( 解密后的二进串 +byte hex (clearByte ))

// System out println ( 解密后的字符串 +(new String (clearByte )))

//

// }

return clearByte;

}

public static byte[] decryptData(byte[] input) throws Exception {

return decryptData(input DEFAULT_KEY)

}

/**

* 字节码转换成 进制字符串

*

* @param byte[] b 输入要转换的字节码

* @return String 返回转换后的 进制字符串

*/

public static String byte hex(byte[] bytes) {

StringBuilder hs = new StringBuilder()

for(byte b : bytes)

hs append(String format( % $ X b))

return hs toString()

}

public static byte[] hex byte(String content) {

int l=content length()》 ;

byte[] result=new byte[l];

for(int i= ;i<l;i++) {

int j=i《 ;

String s=content substring(j j+ )

result[i]=Integer valueOf(s ) byteValue()

}

return result;

}

/**

* 将字节数组转换为base 编码字符串

* @param buffer

* @return

*/

public static String bytesToBase (byte[] buffer) {

//BASE Encoder en=new BASE Encoder()

return Base encode(buffer)

// return encoder encode(buffer)

}

/**

* 将base 编码的字符串解码为字节数组

* @param value

* @return

* @throws IOException

*/

public static byte[] base ToBytes(String value) throws IOException {

//return Base decodeToByteArray(value)

// System out println(decoder decodeBuffer(value))

// return decoder decodeBuffer(value)

return Base decode(value)

}

/**

* 加密给定的字符串

* @param value

* @return 加密后的base 字符串

*/

public static String encryptString(String value) {

return encryptString(value DEFAULT_KEY)

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 以BASE 形式存在的密钥

* @return 加密后的base 字符串

* @throws IOException

*/

public static String encryptString(String value String key) throws IOException {

return encryptString(value base ToBytes(key))

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 字节数组形式的密钥

* @return 加密后的base 字符串

*/

public static String encryptString(String value byte[] key) {

try {

byte[] data=value getBytes(VALUE_ENCODING)

data=CryptUtils encryptData(data key)

return bytesToBase (data)

} catch (Exception e) {

// TODO Auto generated catch block

e printStackTrace()

return null;

}

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @return 明文

*/

public static String decryptString(String value) {

return decryptString(value DEFAULT_KEY)

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key base 形式存在的密钥

* @return 明文

* @throws IOException

*/

public static String decryptString(String value String key) throws IOException {

String s=decryptString(value base ToBytes(key))

return s;

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key 字节数据形式存在的密钥

* @return 明文

*/

public static String decryptString(String value byte[] key) {

try {

byte[] data=base ToBytes(value)

data=CryptUtils decryptData(data key)

return new String(data VALUE_ENCODING)

}catch(Exception e) {

e printStackTrace()

return null;

}

}

}

package gdie lab crypt;

import java io IOException;

import javax crypto Cipher;

import javax crypto KeyGenerator;

import javax crypto SecretKey;

import apache xerces internal impl dv util Base ;

public class CryptUtils {

private static String Algorithm = DES ;

private static byte[] DEFAULT_KEY=new byte[] { };

private static String VALUE_ENCODING= UTF ;

/**

* 生成密钥

*

* @return byte[] 返回生成的密钥

* @throws exception

* 扔出异常

*/

public static byte[] getSecretKey() throws Exception {

KeyGenerator keygen = KeyGenerator getInstance(Algorithm)

SecretKey deskey = keygen generateKey()

// if (debug ) System out println ( 生成密钥 +byte hex (deskey getEncoded

// ()))

return deskey getEncoded()

}

/**

* 将指定的数据根据提供的密钥进行加密

*

* @param input

* 需要加密的数据

* @param key

* 密钥

* @return byte[] 加密后的数据

* @throws Exception

*/

public static byte[] encryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug )

// {

// System out println ( 加密前的二进串 +byte hex (input ))

// System out println ( 加密前的字符串 +new String (input ))

//

// }

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher ENCRYPT_MODE deskey)

byte[] cipherByte = c doFinal(input)

// if (debug ) System out println ( 加密后的二进串 +byte hex (cipherByte ))

return cipherByte;

}

public static byte[] encryptData(byte[] input) throws Exception {

return encryptData(input DEFAULT_KEY)

}

/**

* 将给定的已加密的数据通过指定的密钥进行解密

*

* @param input

* 待解密的数据

* @param key

* 密钥

* @return byte[] 解密后的数据

* @throws Exception

*/

public static byte[] decryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug ) System out println ( 解密前的信息 +byte hex (input ))

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher DECRYPT_MODE deskey)

byte[] clearByte = c doFinal(input)

// if (debug )

// {

// System out println ( 解密后的二进串 +byte hex (clearByte ))

// System out println ( 解密后的字符串 +(new String (clearByte )))

//

// }

return clearByte;

}

public static byte[] decryptData(byte[] input) throws Exception {

return decryptData(input DEFAULT_KEY)

}

/**

* 字节码转换成 进制字符串

*

* @param byte[] b 输入要转换的字节码

* @return String 返回转换后的 进制字符串

*/

public static String byte hex(byte[] bytes) {

StringBuilder hs = new StringBuilder()

for(byte b : bytes)

hs append(String format( % $ X b))

return hs toString()

}

public static byte[] hex byte(String content) {

int l=content length()》 ;

byte[] result=new byte[l];

for(int i= ;i<l;i++) {

int j=i《 ;

String s=content substring(j j+ )

result[i]=Integer valueOf(s ) byteValue()

}

return result;

}

/**

* 将字节数组转换为base 编码字符串

* @param buffer

* @return

*/

public static String bytesToBase (byte[] buffer) {

//BASE Encoder en=new BASE Encoder()

return Base encode(buffer)

// return encoder encode(buffer)

}

/**

* 将base 编码的字符串解码为字节数组

* @param value

* @return

* @throws IOException

*/

public static byte[] base ToBytes(String value) throws IOException {

//return Base decodeToByteArray(value)

// System out println(decoder decodeBuffer(value))

// return decoder decodeBuffer(value)

return Base decode(value)

}

/**

* 加密给定的字符串

* @param value

* @return 加密后的base 字符串

*/

public static String encryptString(String value) {

return encryptString(value DEFAULT_KEY)

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 以BASE 形式存在的密钥

* @return 加密后的base 字符串

* @throws IOException

*/

public static String encryptString(String value String key) throws IOException {

return encryptString(value base ToBytes(key))

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 字节数组形式的密钥

* @return 加密后的base 字符串

*/

public static String encryptString(String value byte[] key) {

try {

byte[] data=value getBytes(VALUE_ENCODING)

data=CryptUtils encryptData(data key)

return bytesToBase (data)

} catch (Exception e) {

// TODO Auto generated catch block

e printStackTrace()

return null;

}

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @return 明文

*/

public static String decryptString(String value) {

return decryptString(value DEFAULT_KEY)

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key base 形式存在的密钥

* @return 明文

* @throws IOException

*/

public static String decryptString(String value String key) throws IOException {

String s=decryptString(value base ToBytes(key))

return s;

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key 字节数据形式存在的密钥

* @return 明文

*/

public static String decryptString(String value byte[] key) {

try {

byte[] data=base ToBytes(value)

data=CryptUtils decryptData(data key)

return new String(data VALUE_ENCODING)

}catch(Exception e) {

e printStackTrace()

return null;

}

}

}

CryptHelper java

[java]

package gdie lab crypt;

import javax crypto Cipher;

import javax crypto SecretKey;

import javax crypto SecretKeyFactory;

import javax crypto spec DESKeySpec;

import javax crypto spec IvParameterSpec;

import springframework util DigestUtils;

public class CryptHelper{

private static String CRYPT_KEY = zhongqian ;

//加密

private static Cipher ecip;

//解密

private static Cipher dcip;

static {

try {

String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()

KEY = KEY substring( )

byte[] bytes = KEY getBytes()

DESKeySpec ks = new DESKeySpec(bytes)

SecretKeyFactory skf = SecretKeyFactory getInstance( DES )

SecretKey sk = skf generateSecret(ks)

IvParameterSpec iv = new IvParameterSpec(bytes)

ecip = Cipher getInstance( DES/CBC/PKCS Padding )

ecip init(Cipher ENCRYPT_MODE sk iv )

dcip = Cipher getInstance( DES/CBC/PKCS Padding )

dcip init(Cipher DECRYPT_MODE sk iv )

}catch(Exception ex) {

ex printStackTrace()

}

}

public static String encrypt(String content) throws Exception {

byte[] bytes = ecip doFinal(content getBytes( ascii ))

return CryptUtils byte hex(bytes)

}

public static String decrypt(String content) throws Exception {

byte[] bytes = CryptUtils hex byte(content)

bytes = dcip doFinal(bytes)

return new String(bytes ascii )

}

//test

public static void main(String[] args) throws Exception {

String password = gly ;

String en = encrypt(password)

System out println(en)

System out println(decrypt(en))

}

}

package gdie lab crypt;

import javax crypto Cipher;

import javax crypto SecretKey;

import javax crypto SecretKeyFactory;

import javax crypto spec DESKeySpec;

import javax crypto spec IvParameterSpec;

import springframework util DigestUtils;

public class CryptHelper{

private static String CRYPT_KEY = zhongqian ;

//加密

private static Cipher ecip;

//解密

private static Cipher dcip;

static {

try {

String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()

KEY = KEY substring( )

byte[] bytes = KEY getBytes()

DESKeySpec ks = new DESKeySpec(bytes)

SecretKeyFactory skf = SecretKeyFactory getInstance( DES )

SecretKey sk = skf generateSecret(ks)

IvParameterSpec iv = new IvParameterSpec(bytes)

ecip = Cipher getInstance( DES/CBC/PKCS Padding )

ecip init(Cipher ENCRYPT_MODE sk iv )

dcip = Cipher getInstance( DES/CBC/PKCS Padding )

dcip init(Cipher DECRYPT_MODE sk iv )

}catch(Exception ex) {

ex printStackTrace()

}

}

public static String encrypt(String content) throws Exception {

byte[] bytes = ecip doFinal(content getBytes( ascii ))

return CryptUtils byte hex(bytes)

}

public static String decrypt(String content) throws Exception {

byte[] bytes = CryptUtils hex byte(content)

bytes = dcip doFinal(bytes)

return new String(bytes ascii )

}

//test

public static void main(String[] args) throws Exception {

String password = gly ;

String en = encrypt(password)

System out println(en)

System out println(decrypt(en))

}

lishixin/Article/program/Java/hx/201311/26449

‘陆’ 怎样为一个java程序加密 谢谢

只给编译后的.jar文件,不给.java文件

不过要说明的是,java因为是字节码,所以没有办法防止被反编译。
最多也就是做一下代码混淆,比如把方法或变量名改成无意义的名称,或者加一些完全无用的代码进去,让恶意攻击的人难以看懂

‘柒’ 如何用JAVA实现字符串简单加密解密

java加密字符串可以使用des加密算法,实例如下:
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
/**
* 加密解密
*
* @author shy.qiu
* @since
*/
public class CryptTest {
/**
* 进行MD5加密
*
* @param info
* 要加密的信息
* @return String 加密后的字符串
*/
public String encryptToMD5(String info) {
byte[] digesta = null;
try {
// 得到一个md5的消息摘要
MessageDigest alga = MessageDigest.getInstance("MD5");
// 添加要进行计算摘要的信息
alga.update(info.getBytes());
// 得到该摘要
digesta = alga.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 将摘要转为字符串
String rs = byte2hex(digesta);
return rs;
}
/**
* 进行SHA加密
*
* @param info
* 要加密的信息
* @return String 加密后的字符串
*/
public String encryptToSHA(String info) {
byte[] digesta = null;
try {
// 得到一个SHA-1的消息摘要
MessageDigest alga = MessageDigest.getInstance("SHA-1");
// 添加要进行计算摘要的信息
alga.update(info.getBytes());
// 得到该摘要
digesta = alga.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 将摘要转为字符串
String rs = byte2hex(digesta);
return rs;
}
// //////////////////////////////////////////////////////////////////////////
/**
* 创建密匙
*
* @param algorithm
* 加密算法,可用 DES,DESede,Blowfish
* @return SecretKey 秘密(对称)密钥
*/
public SecretKey createSecretKey(String algorithm) {
// 声明KeyGenerator对象
KeyGenerator keygen;
// 声明 密钥对象
SecretKey deskey = null;
try {
// 返回生成指定算法的秘密密钥的 KeyGenerator 对象
keygen = KeyGenerator.getInstance(algorithm);
// 生成一个密钥
deskey = keygen.generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 返回密匙
return deskey;
}
/**
* 根据密匙进行DES加密
*
* @param key
* 密匙
* @param info
* 要加密的信息
* @return String 加密后的信息
*/
public String encryptToDES(SecretKey key, String info) {
// 定义 加密算法,可用 DES,DESede,Blowfish
String Algorithm = "DES";
// 加密随机数生成器 (RNG),(可以不写)
SecureRandom sr = new SecureRandom();
// 定义要生成的密文
byte[] cipherByte = null;
try {
// 得到加密/解密器
Cipher c1 = Cipher.getInstance(Algorithm);
// 用指定的密钥和模式初始化Cipher对象
// 参数:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)
c1.init(Cipher.ENCRYPT_MODE, key, sr);
// 对要加密的内容进行编码处理,
cipherByte = c1.doFinal(info.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
// 返回密文的十六进制形式
return byte2hex(cipherByte);
}
/**
* 根据密匙进行DES解密
*
* @param key
* 密匙
* @param sInfo
* 要解密的密文
* @return String 返回解密后信息
*/
public String decryptByDES(SecretKey key, String sInfo) {
// 定义 加密算法,
String Algorithm = "DES";
// 加密随机数生成器 (RNG)
SecureRandom sr = new SecureRandom();
byte[] cipherByte = null;
try {
// 得到加密/解密器
Cipher c1 = Cipher.getInstance(Algorithm);
// 用指定的密钥和模式初始化Cipher对象
c1.init(Cipher.DECRYPT_MODE, key, sr);
// 对要解密的内容进行编码处理
cipherByte = c1.doFinal(hex2byte(sInfo));
} catch (Exception e) {
e.printStackTrace();
}
// return byte2hex(cipherByte);
return new String(cipherByte);
}
// /////////////////////////////////////////////////////////////////////////////
/**
* 创建密匙组,并将公匙,私匙放入到指定文件中
*
* 默认放入mykeys.bat文件中
*/
public void createPairKey() {
try {
// 根据特定的算法一个密钥对生成器
KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
// 加密随机数生成器 (RNG)
SecureRandom random = new SecureRandom();
// 重新设置此随机对象的种子
random.setSeed(1000);
// 使用给定的随机源(和默认的参数集合)初始化确定密钥大小的密钥对生成器
keygen.initialize(512, random);// keygen.initialize(512);
// 生成密钥组
KeyPair keys = keygen.generateKeyPair();
// 得到公匙
PublicKey pubkey = keys.getPublic();
// 得到私匙
PrivateKey prikey = keys.getPrivate();
// 将公匙私匙写入到文件当中
doObjToFile("mykeys.bat", new Object[] { prikey, pubkey });
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
/**
* 利用私匙对信息进行签名 把签名后的信息放入到指定的文件中
*
* @param info
* 要签名的信息
* @param signfile
* 存入的文件
*/
public void signToInfo(String info, String signfile) {
// 从文件当中读取私匙
PrivateKey myprikey = (PrivateKey) getObjFromFile("mykeys.bat", 1);
// 从文件中读取公匙
PublicKey mypubkey = (PublicKey) getObjFromFile("mykeys.bat", 2);
try {
// Signature 对象可用来生成和验证数字签名
Signature signet = Signature.getInstance("DSA");
// 初始化签署签名的私钥
signet.initSign(myprikey);
// 更新要由字节签名或验证的数据
signet.update(info.getBytes());
// 签署或验证所有更新字节的签名,返回签名
byte[] signed = signet.sign();
// 将数字签名,公匙,信息放入文件中
doObjToFile(signfile, new Object[] { signed, mypubkey, info });
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 读取数字签名文件 根据公匙,签名,信息验证信息的合法性
*
* @return true 验证成功 false 验证失败
*/
public boolean validateSign(String signfile) {
// 读取公匙
PublicKey mypubkey = (PublicKey) getObjFromFile(signfile, 2);
// 读取签名
byte[] signed = (byte[]) getObjFromFile(signfile, 1);
// 读取信息
String info = (String) getObjFromFile(signfile, 3);
try {
// 初始一个Signature对象,并用公钥和签名进行验证
Signature signetcheck = Signature.getInstance("DSA");
// 初始化验证签名的公钥
signetcheck.initVerify(mypubkey);
// 使用指定的 byte 数组更新要签名或验证的数据
signetcheck.update(info.getBytes());
System.out.println(info);
// 验证传入的签名
return signetcheck.verify(signed);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将二进制转化为16进制字符串
*
* @param b
* 二进制字节数组
* @return String
*/
public String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
/**
* 十六进制字符串转化为2进制
*
* @param hex
* @return
*/
public byte[] hex2byte(String hex) {
byte[] ret = new byte[8];
byte[] tmp = hex.getBytes();
for (int i = 0; i < 8; i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
/**
* 将两个ASCII字符合成一个字节; 如:"EF"--> 0xEF
*
* @param src0
* byte
* @param src1
* byte
* @return byte
*/
public static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
.byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
.byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
/**
* 将指定的对象写入指定的文件
*
* @param file
* 指定写入的文件
* @param objs
* 要写入的对象
*/
public void doObjToFile(String file, Object[] objs) {
ObjectOutputStream oos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
for (int i = 0; i < objs.length; i++) {
oos.writeObject(objs[i]);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 返回在文件中指定位置的对象
*
* @param file
* 指定的文件
* @param i
* 从1开始
* @return
*/
public Object getObjFromFile(String file, int i) {
ObjectInputStream ois = null;
Object obj = null;
try {
FileInputStream fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
for (int j = 0; j < i; j++) {
obj = ois.readObject();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return obj;
}
/**
* 测试
*
* @param args
*/
public static void main(String[] args) {
CryptTest jiami = new CryptTest();
// 执行MD5加密"Hello world!"
System.out.println("Hello经过MD5:" + jiami.encryptToMD5("Hello"));
// 生成一个DES算法的密匙
SecretKey key = jiami.createSecretKey("DES");
// 用密匙加密信息"Hello world!"
String str1 = jiami.encryptToDES(key, "Hello");
System.out.println("使用des加密信息Hello为:" + str1);
// 使用这个密匙解密
String str2 = jiami.decryptByDES(key, str1);
System.out.println("解密后为:" + str2);
// 创建公匙和私匙
jiami.createPairKey();
// 对Hello world!使用私匙进行签名
jiami.signToInfo("Hello", "mysign.bat");
// 利用公匙对签名进行验证。
if (jiami.validateSign("mysign.bat")) {
System.out.println("Success!");
} else {
System.out.println("Fail!");
}
}
}

‘捌’ java最常用的几种加密算法

简单的Java加密算法有:
第一种. BASE
Base是网络上最常见的用于传输Bit字节代码的编码方式之一,大家可以查看RFC~RFC,上面有MIME的详细规范。Base编码可用于在HTTP环境下传递较长的标识信息。例如,在Java Persistence系统Hibernate中,就采用了Base来将一个较长的唯一标识符(一般为-bit的UUID)编码为一个字符串,用作HTTP表单和HTTP GET URL中的参数。在其他应用程序中,也常常需要把二进制数据编码为适合放在URL(包括隐藏表单域)中的形式。此时,采用Base编码具有不可读性,即所编码的数据不会被人用肉眼所直接看到。
第二种. MD
MD即Message-Digest Algorithm (信息-摘要算法),用于确保信息传输完整一致。是计算机广泛使用的杂凑算法之一(又译摘要算法、哈希算法),主流编程语言普遍已有MD实现。将数据(如汉字)运算为另一固定长度值,是杂凑算法的基础原理,MD的前身有MD、MD和MD。
MD算法具有以下特点:
压缩性:任意长度的数据,算出的MD值长度都是固定的。
容易计算:从原数据计算出MD值很容易。
抗修改性:对原数据进行任何改动,哪怕只修改个字节,所得到的MD值都有很大区别。
弱抗碰撞:已知原数据和其MD值,想找到一个具有相同MD值的数据(即伪造数据)是非常困难的。
强抗碰撞:想找到两个不同的数据,使它们具有相同的MD值,是非常困难的。
MD的作用是让大容量信息在用数字签名软件签署私人密钥前被”压缩”成一种保密的格式(就是把一个任意长度的字节串变换成一定长的十六进制数字串)。除了MD以外,其中比较有名的还有sha-、RIPEMD以及Haval等。
第三种.SHA
安全哈希算法(Secure Hash Algorithm)主要适用于数字签名标准(Digital Signature Standard DSS)里面定义的数字签名算法(Digital Signature Algorithm DSA)。对于长度小于^位的消息,SHA会产生一个位的消息摘要。该算法经过加密专家多年来的发展和改进已日益完善,并被广泛使用。该算法的思想是接收一段明文,然后以一种不可逆的方式将它转换成一段(通常更小)密文,也可以简单的理解为取一串输入码(称为预映射或信息),并把它们转化为长度较短、位数固定的输出序列即散列值(也称为信息摘要或信息认证代码)的过程。散列函数值可以说是对明文的一种“指纹”或是“摘要”所以对散列值的数字签名就可以视为对此明文的数字签名。
SHA-与MD的比较
因为二者均由MD导出,SHA-和MD彼此很相似。相应的,他们的强度和其他特性也是相似,但还有以下几点不同:
对强行攻击的安全性:最显着和最重要的区别是SHA-摘要比MD摘要长 位。使用强行技术,产生任何一个报文使其摘要等于给定报摘要的难度对MD是^数量级的操作,而对SHA-则是^数量级的操作。这样,SHA-对强行攻击有更大的强度。
对密码分析的安全性:由于MD的设计,易受密码分析的攻击,SHA-显得不易受这样的攻击。
速度:在相同的硬件上,SHA-的运行速度比MD慢。
第四种.HMAC
HMAC(Hash Message Authentication Code,散列消息鉴别码,基于密钥的Hash算法的认证协议。消息鉴别码实现鉴别的原理是,用公开函数和密钥产生一个固定长度的值作为认证标识,用这个标识鉴别消息的完整性。使用一个密钥生成一个固定大小的小数据块,即MAC,并将其加入到消息中,然后传输。接收方利用与发送方共享的密钥进行鉴别认证等。

‘玖’ java中使用MD5加密算法进行加密

在各种应用系统的开发中 经常需要存储用户信息 很多地方都要存储用户密码 而将用户密码直接存储亮衫唯在服务器上显然是不安全的 本文简要介绍工作中常用的 MD 加密算法 希望能抛砖引玉

(一)消息摘要简介

一个消息摘要就是一个数据块的数字指纹 即对一个任意敬培长度的一个数据块进行计算 产生一个唯一指印(对于SHA 是产生一个 字节的二进制数组) 消息摘要是一种与消息认证码结合使用以确保消息完整性的技术 主要使用单向散列函数算法 可用于检验消息的完整性 和通过散列密码直接以文本形式保存等 目前广泛使用的算法有MD MD SHA

消息摘要有两个基本属性

两个不同的报文难以生成相同的摘要难以对指定的摘要生成一个报文 而可以由该报文反推算出该指定的摘要代表 美国国家标准技术研究所的SHA 和麻省理工学院Ronald Rivest提出的MD

(二)对字符串进行加密

/***//**利用MD 进行加密*@paramstr待加密的字符串*@return加密后的字符串*塌仔@没有这种产生消息摘要的算法*@*/publicStringEncoderByMd (Stringstr) UnsupportedEncodingException {//确定计算方法MessageDigestmd =MessageDigest getInstance( MD );BASE Encoderbase en=newBASE Encoder();//加密后的字符串Stringnewstr=base en encode(md digest(str getBytes( utf )));returnnewstr;}

调用函数 String str=

System out println(EncoderByMd (str))

输出 eB eJF ptWaXm bijSPyxw==

(三)验证密码是否正确

/***//**判断用户密码是否正确*@paramnewpasswd用户输入的密码*@paramoldpasswd数据库中存储的密码--用户密码的摘要*@return*@*@*/publicbooleancheckpassword(Stringnewpasswd Stringoldpasswd) UnsupportedEncodingException {if(EncoderByMd (newpasswd) equals(oldpasswd))returntrue;elsereturnfalse;} lishixin/Article/program/Java/hx/201311/26374

热点内容
oppor9s怎么压缩文件 发布:2025-02-05 15:00:34 浏览:637
苹果耳塞怎么改安卓也能用 发布:2025-02-05 14:50:54 浏览:557
安卓如何鉴别手机真假 发布:2025-02-05 14:28:15 浏览:119
ffmpeglinux编译 发布:2025-02-05 14:28:04 浏览:544
服务器如何做界面 发布:2025-02-05 14:27:23 浏览:290
访问学者单位推荐意见 发布:2025-02-05 14:13:05 浏览:853
微信密码锁忘了怎么办 发布:2025-02-05 14:11:07 浏览:311
web是什么文件夹 发布:2025-02-05 14:11:05 浏览:235
对信访问题调查 发布:2025-02-05 14:09:39 浏览:984
singlephp 发布:2025-02-05 14:09:24 浏览:774