當前位置:首頁 » 編程語言 » javaphpaes

javaphpaes

發布時間: 2024-01-17 16:59:11

php AES加密對不上java的加密,請問如何實現

要注意特定的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;i<len;i++)
result[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;i<buf.length;i++){
appendHex(result,buf[i]);
}
returnresult.toString();
}
privatefinalstaticStringHEX="0123456789ABCDEF";
privatestaticvoidappendHex(StringBuffersb,byteb){
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}

}

熱點內容
機加工的編程 發布:2024-11-30 00:31:19 瀏覽:727
坦克世界電腦什麼配置 發布:2024-11-30 00:30:41 瀏覽:317
如何在手機設置上找到網路的密碼 發布:2024-11-30 00:18:29 瀏覽:414
和鷹加密鎖 發布:2024-11-30 00:17:17 瀏覽:556
C語言舞會 發布:2024-11-30 00:15:44 瀏覽:377
java下載我的世界 發布:2024-11-30 00:11:08 瀏覽:12
華三配置器升級失敗怎麼回事 發布:2024-11-30 00:09:23 瀏覽:842
汽車空調壓縮機壽命 發布:2024-11-30 00:06:04 瀏覽:567
電腦網路波動異常與伺服器失去連接 發布:2024-11-29 23:43:19 瀏覽:247
個人電腦與伺服器架構類似 發布:2024-11-29 23:40:59 瀏覽:705