当前位置:首页 » 编程语言 » 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));
}

}

热点内容
随机启动脚本 发布:2025-07-05 16:10:30 浏览:528
微博数据库设计 发布:2025-07-05 15:30:55 浏览:25
linux485 发布:2025-07-05 14:38:28 浏览:305
php用的软件 发布:2025-07-05 14:06:22 浏览:756
没有权限访问计算机 发布:2025-07-05 13:29:11 浏览:433
javaweb开发教程视频教程 发布:2025-07-05 13:24:41 浏览:707
康师傅控流脚本破解 发布:2025-07-05 13:17:27 浏览:243
java的开发流程 发布:2025-07-05 12:45:11 浏览:687
怎么看内存卡配置 发布:2025-07-05 12:29:19 浏览:285
访问学者英文个人简历 发布:2025-07-05 12:29:17 浏览:835