java和php加解密对接
之前写过一个java和php的加解密对接文章,好像解密后有部分字符串乱码,现在重新给一个加解密的对接方案:
java代码:
import java.util.UUID; import org.apache.commons.codec.binary.Base64; public class Base64Utility extends Base64 { private static final char last2byte = (char) Integer.parseInt("00000011", 2); private static final char last4byte = (char) Integer.parseInt("00001111", 2); private static final char last6byte = (char) Integer.parseInt("00111111", 2); private static final char lead6byte = (char) Integer.parseInt("11111100", 2); private static final char lead4byte = (char) Integer.parseInt("11110000", 2); private static final char lead2byte = (char) Integer.parseInt("11000000", 2); /** * "+" -> "*"; "/" -> "-" */ private static final char[] encodeTable = new char[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "-" }; /** * @param binaryData * binary data to encode * @return String containing Base64 characters * @since 1.4 */ public static String encodeBase64URLSafeString2(byte[] from) { StringBuffer to = new StringBuffer((int) (from.length * 1.34) + 3); int num = 0; char currentByte = 0; for (int i = 0; i < from.length; i++) { num = num % 8; while (num < 8) { switch (num) { case 0: currentByte = (char) (from[i] & lead6byte); currentByte = (char) (currentByte >>> 2); break; case 2: currentByte = (char) (from[i] & last6byte); break; case 4: currentByte = (char) (from[i] & last4byte); currentByte = (char) (currentByte << 2); if ((i + 1) < from.length) { currentByte |= (from[i + 1] & lead2byte) >>> 6; } break; case 6: currentByte = (char) (from[i] & last2byte); currentByte = (char) (currentByte << 4); if ((i + 1) < from.length) { currentByte |= (from[i + 1] & lead4byte) >>> 4; } break; } to.append(encodeTable[currentByte]); num += 6; } } if (to.length() % 4 != 0) { for (int i = 4 - to.length() % 4; i > 0; i--) { to.append("="); } } return to.toString(); } public static void main(String[] args) { encodeBase64URLSafeString(null); System.out.println(UUID.randomUUID().toString()); } }
import java.security.Key; import javax.crypto.Cipher; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; public class CipherUtility { public static class AES { // 密钥算法 public static final String KEY_ALGORITHM = "AES"; // 加解密算法/工作模式/填充方式,Java6.0支持PKCS5Padding填充方式,BouncyCastle支持PKCS7Padding填充方式 public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding"; /** * 生成密钥 */ protected static Key getKey(String password) throws Exception { // KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM); // 实例化密钥生成器 // kg.init(128, new SecureRandom(password.getBytes()));// 初始化密钥生成器:AES要求密钥长度为128,192,256位 // SecretKey secretKey = kg.generateKey(); // 生成密钥 return new SecretKeySpec(DigestUtility.md5(password.getBytes()), KEY_ALGORITHM); // MD5 128bit } /** * 加密数据 * * @param data * @param password * @return */ public static byte[] encrypt(byte[] data, String password) { try { Key k = getKey(password);// 还原密钥 // 使用PKCS7Padding填充方式,这里就得这么写了(即调用BouncyCastle组件实现) // Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC"); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); // 实例化Cipher对象,它用于完成实际的加密操作 cipher.init(Cipher.ENCRYPT_MODE, k); // 初始化Cipher对象,设置为加密模式 byte[] bytes = cipher.doFinal(data); return bytes; } catch (Exception e) { return null; } } /** * 加密数据 * * @param data * 待加密数据 * @param key * 密钥 * @return 加密后的数据 */ public static String encrypt(String data, String password) { return encrypt(data, password, true); } /** * 加密数据 BASE 64 * * @param data * 待加密数据 * @param key * 密钥 * @return 加密后的数据 */ public static String encrypt(String data, String password, boolean urlSafe) { try { byte[] bytes = encrypt(data.getBytes(), password); if (urlSafe) { // System.out.println(Hex.encodeHexString(bytes)); // System.out.println(Hex.encodeHexString(Base64.encodeBase64(bytes))); return Base64.encodeBase64URLSafeString(bytes); // 执行加密操作。加密后的结果通常都会用Base64编码进行传输 } else { return Base64.encodeBase64String(bytes); // 执行加密操作。加密后的结果通常都会用Base64编码进行传输 } } catch (Exception e) { return null; } } /** * 解密数据 * * @param data * @param password * @return */ public static byte[] decrypt(byte[] data, String password) { try { Key k = getKey(password); // 还原密钥 Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, k); // 初始化Cipher对象,设置为解密模式 byte[] bytes = cipher.doFinal(data);// 执行解密操作 return bytes; } catch (Exception e) { return null; } } /** * 解密数据 * * @param data * 待解密数据 * @param key * 密钥 * @return 解密后的数据 */ public static String decrypt(String data, String password) { try { byte[] bytes = decrypt(Base64.decodeBase64(data), password); return new String(bytes); // 执行解密操作 } catch (Exception e) { return null; } } } public static class HMAC_SHA1 { public static String encrypt(String data, String password) { try { SecretKeySpec signingKey = new SecretKeySpec(password.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(data.getBytes()); String dfd = Base64Utility.encodeBase64URLSafeString2(rawHmac); return dfd; } catch (Exception e) { return null; } } } }
import org.apache.commons.codec.digest.DigestUtils; public class DigestUtility extends DigestUtils { }php代码:
class EncryptController extends Controller{ public static function encrypt($input, $key,$urlsafe = true) { $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); $input = EncryptController::pkcs5_pad($input, $size); $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, "", MCRYPT_MODE_ECB, ""); $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND); mcrypt_generic_init($td, md5($key,true), $iv); $data = mcrypt_generic($td, $input); mcrypt_generic_deinit($td); mcrypt_module_close($td); $data = base64_encode($data); if($urlsafe){ $data = str_replace("+","-",$data); $data = str_replace("/","_",$data); $data = str_replace("=","",$data); } return $data; } private static function pkcs5_pad ($text, $blocksize) { $pad = $blocksize - (strlen($text) % $blocksize); return $text . str_repeat(chr($pad), $pad); } public static function decrypt($sStr, $sKey) { $decrypted= mcrypt_decrypt( MCRYPT_RIJNDAEL_128, md5($sKey,true), base64_decode($sStr), MCRYPT_MODE_ECB ); $dec_s = strlen($decrypted); $padding = ord($decrypted[$dec_s-1]); $decrypted = substr($decrypted, 0, -$padding); return $decrypted; } }
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇: php AES/CBC/PKCS5Padding 与java对接