java和php加解密對接
阿新 • • 發佈:2019-02-08
之前寫過一個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; } }