當前位置:ag真人国际官网-ag旗舰厅官方网站 » 編程語言 » javaphpaes
javaphpaes-ag真人国际官网
發布時間: 2024-01-17 16:59:11
要注意特定的padding實現跟演算法的blocksize有關,這里php的blocksize是在php的aes加密前先對源字元串進行padding,問題得到解決。
㈡ 怎麼把php aes128的代碼轉成java
publicclasssimplecrypto{
publicstaticstringencrypt(stringseed,stringcleartext)throwsexception{
byte[]rawkey=getrawkey(seed.getbytes());
byte[]result=encrypt(rawkey,cleartext.getbytes());
returntohex(result);
}
publicstaticstringdecrypt(stringseed,stringencrypted)throwsexception{
byte[]rawkey=getrawkey(seed.getbytes());
byte[]enc=tobyte(encrypted);
byte[]result=decrypt(rawkey,enc);
returnnewstring(result);
}
privatestaticbyte[]getrawkey(byte[]seed)throwsexception{
keygeneratorkgen=keygenerator.getinstance("aes");
securerandomsr=securerandom.getinstance("sha1prng");
sr.setseed(seed);
kgen.init(128,sr);//
secretkeyskey=kgen.generatekey();
byte[]raw=skey.getencoded();
returnraw;
}
privatestaticbyte[]encrypt(byte[]raw,byte[]clear)throwsexception{
secretkeyspecskeyspec=newsecretkeyspec(raw,"aes");
ciphercipher=cipher.getinstance("aes");
cipher.init(cipher.encrypt_mode,skeyspec);
byte[]encrypted=cipher.dofinal(clear);
returnencrypted;
}
privatestaticbyte[]decrypt(byte[]raw,byte[]encrypted)throwsexception{
secretkeyspecskeyspec=newsecretkeyspec(raw,"aes");
ciphercipher=cipher.getinstance("aes");
cipher.init(cipher.decrypt_mode,skeyspec);
byte[]decrypted=cipher.dofinal(encrypted);
returndecrypted;
}
publicstaticstringtohex(stringtxt){
returntohex(txt.getbytes());
}
publicstaticstringfromhex(stringhex){
returnnewstring(tobyte(hex));
}
publicstaticbyte[]tobyte(stringhexstring){
intlen=hexstring.length()/2;
byte[]result=newbyte[len];
for(inti=0;iresult[i]=integer.valueof(hexstring.substring(2*i,2*i 2),16).bytevalue();
returnresult;
}
publicstaticstringtohex(byte[]buf){
if(buf==null)
return"";
stringbufferresult=newstringbuffer(2*buf.length);
for(inti=0;iappendhex(result,buf[i]);
}
returnresult.tostring();
}
privatefinalstaticstringhex="0123456789abcdef";
privatestaticvoidappendhex(stringbuffersb,byteb){
sb.append(hex.charat((b>>4)&0x0f)).append(hex.charat(b&0x0f));
}
}
熱點內容