/** * 加密方法 * @param string $str * @return string */ function encrypt($str, $screct_key) { //AES, 128 模式加密数据 CBC $screct_key = base64_decode($screct_key); $str = trim($str); $str = addPKCS7Padding($str); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), 1); $encrypt_str = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC); return base64_encode($encrypt_str); }
function encryptAES128ECB($data, $key) { $blocks = str_split($data, 16); $numBlocks = count($blocks); if (strlen($blocks[$numBlocks - 1]) === 16) { $blocks[] = addPKCS7Padding('', 16); } else { $blocks[$numBlocks - 1] = addPKCS7Padding($blocks[$numBlocks - 1], 16); } foreach ($blocks as &$block) { $block = _encryptAES128ECB($block, $key); } return implode($blocks); }
* http://cryptopals.com/sets/2/challenges/9/ * * Implement PKCS#7 padding * * A block cipher transforms a fixed-sized block (usually 8 or 16 bytes) of plaintext into ciphertext. But we almost never want to transform a single block; we encrypt irregularly-sized messages. * * One way we account for irregularly-sized messages is by padding, creating a plaintext that is an even multiple of the blocksize. The most popular padding scheme is called PKCS#7. * * So: pad any block to a specific block length, by appending the number of bytes of padding to the end of the block. For instance, * "YELLOW SUBMARINE" * * ... padded to 20 bytes would be: * "YELLOW SUBMARINE\x04\x04\x04\x04" */ function addPKCS7Padding($data, $padTo = 16) { $dataLen = strlen($data); $padLen = $padTo - $dataLen % $padTo; return $data . str_repeat(chr($padLen), $padLen); } // don't output if we're included into another script. if (!debug_backtrace()) { $success = true; $success &= addPKCS7Padding('YELLOW SUBMARINE', 20) === "YELLOW SUBMARINE"; $success &= addPKCS7Padding('YELLOW SUBMARINE', 10) === "YELLOW SUBMARINE"; $success &= addPKCS7Padding('YELLOW SUBMARINE', 6) === "YELLOW SUBMARINE"; // make sure a full block of padding is added when the data length is a multiple of the pad length $success &= addPKCS7Padding('YELLOW SUBMARINE', 8) === "YELLOW SUBMARINE"; $success &= addPKCS7Padding('', 4) === ""; print $success ? "Success!\n\n" : "Failure :(\n\n"; }