AES多语言加解密笔记!

php:

mcrypt_decrypt改成openssl_decrypt

$decode = self::stripPkcs7Padding(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, self::KEY, self::hexToStr($data), MCRYPT_MODE_CBC, self::IV_16)); //php5可正常解密

$decode = openssl_decrypt (hex2bin($datas->data), 'AES-128-CBC', $key, OPENSSL_RAW_DATA,$iv);//php7解密
class Crypter{

    CONST IV_32 = '12345678901234561234567890123456';

    CONST IV_16 = '1234567890123456';

    CONST KEY = '1234567890123456';



    /**
     * aes256cbc加密
     * @param 加密的初始向量(IV的长度必须和Blocksize一样, 且加密和解密一定要用相同的IV)
     */
    public static function aes256cbcEncrypt($data) {
        return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, self::KEY, self::addPkcs7Padding(json_encode($data)) , MCRYPT_MODE_CBC, self::IV_32));
    }

    /**
     * aes256cbc解密
     * @return String
     */
    public static function aes256cbcDecrypt($encryptedText) {
         return json_decode(self::stripPkcs7Padding(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, self::KEY, base64_decode($encryptedText), MCRYPT_MODE_CBC, self::IV_32)),true);
    }

    /*
     * aes128加密
     */
    public static function aes128cbcEncrypt($data) {
        return $base = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, self::KEY,self::addPkcs7Padding(json_encode($data),16) , MCRYPT_MODE_CBC, self::IV_16));
    }

    /*
     * aes128解密
     */
    public static function aes128cbcDecrypt($data) {
        return json_decode(self::stripPkcs7Padding(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, self::KEY, base64_decode($data), MCRYPT_MODE_CBC, self::IV_16)));
    }

    /*
     * aes128加密
     */
    public static function aes128cbcHexEncrypt($data) {
        return self::strToHex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, self::KEY,self::addPkcs7Padding(json_encode($data),16) , MCRYPT_MODE_CBC, self::IV_16));
    }

    /*
     * aes128解密
     */
    public static function aes128cbcHexDecrypt($data) {
        return self::stripPkcs7Padding(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, self::KEY, self::hexToStr($data), MCRYPT_MODE_CBC, self::IV_16));

    }


    /**
     * pkcs7补码,Blocksize以byte为单位
     */
    private static function addPkcs7Padding($string, $blocksize = 32) {
        $len = strlen($string); //取得字符串长度
        $pad = $blocksize - ($len % $blocksize); //取得补码的长度
        $string .= str_repeat(chr($pad), $pad); //用ASCII码为补码长度的字符, 补足最后一段
        return $string;
    }

    /*
     * 除去pkcs7 padding
     */
    private  static function stripPkcs7Padding($string){
        $slast = ord(substr($string, -1));
        $slastc = chr($slast);
        $pcheck = substr($string, -$slast);

        if(preg_match("/$slastc{".$slast."}/", $string)){
            $string = substr($string, 0, strlen($string)-$slast);
            return $string;
        } else {
            return false;
        }
    }

    /*
     * 十六进制转字符串
     */
    private static function hexToStr($hex)
    {
        $string="";
        for($i=0;$i<strlen($hex)-1;$i+=2)
            $string.=chr(hexdec($hex[$i].$hex[$i+1]));
        return  $string;
    }

    /*
     * 字符串转十六进制
     */
    private static function strToHex($string)
    {
        $hex="";
        for($i=0;$i<strlen($string);$i++)
        {
            $tmp = dechex(ord($string[$i]));
            $hex.= strlen($tmp) == 1 ? "0".$tmp : $tmp;
        }
        return strtoupper($hex);
    }

}

IOS:

 //对数据进行解密
    NSData* result = [data aes256_decrypt:key];
    if (result && result.length > 0) {
        return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    }
    return nil;
}
@end





@implementation NSData (AES256)

- (NSData *)aes256_encrypt:(NSString *)key   //加密
{
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding ,
                                          keyPtr, kCCBlockSizeAES128,
                                          [AES_IV UTF8String],
                                          [self bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    free(buffer);
    return nil;
}

- (NSData *)aes256_decrypt:(NSString *)key   //解密
{
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding ,
                                          keyPtr, kCCBlockSizeAES128,
                                          [AES_IV UTF8String],
                                          [self bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];

    }
    free(buffer);
    return nil;
}

@end

android:

package com.example.aes;


import java.io.UnsupportedEncodingException;


import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


/**
 * AES加密解密算法
 */
public class AesEncryptionUtil {
    /** 算法/模式/填充 **/
    private static final String CipherMode = "AES/CBC/PKCS5Padding";


    /** 创建密钥 **/
    private static SecretKeySpec createKey(String key) {
        byte[] data = null;
        if (key == null) {
            key = "";
        }
        StringBuffer sb = new StringBuffer(16);
        sb.append(key);
        while (sb.length() < 16) {
            sb.append("0");
        }
        if (sb.length() > 16) {
            sb.setLength(16);
        }


        try {
            data = sb.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new SecretKeySpec(data, "AES");
    }


    private static IvParameterSpec createIV(String password) {
        byte[] data = null;
        if (password == null) {
            password = "";
        }
    StringBuffer sb = new StringBuffer(16);
        sb.append(password);
        while (sb.length() < 16) {
            sb.append("0");
        }
        if (sb.length() > 16) {
            sb.setLength(16);
        }


        try {
            data = sb.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new IvParameterSpec(data);
    }


    /** 加密字节数据 **/
    public static byte[] encrypt(byte[] content, String password, String iv) {
        try {
            SecretKeySpec key = createKey(password);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, key, createIV(iv));
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /** 加密(结果为16进制字符串) **/
    public static String encrypt(String content, String password, String iv) {
        byte[] data = null;
        try {
            data = content.getBytes("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = encrypt(data, password, iv);
        String result = byte2hex(data);
        return result;
    }


    /** 解密字节数组 **/
    public static byte[] decrypt(byte[] content, String password, String iv) {
        try {
            SecretKeySpec key = createKey(password);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.DECRYPT_MODE, key, createIV(iv));
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /** 解密(输出结果为字符串) **/
    public static String decrypt(String content, String password, String iv) {
        byte[] data = null;
        try {
            data = hex2byte(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = decrypt(data, password, iv);
        if (data == null)
            return null;
        String result = null;
        try {
            result = new String(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }


    /** 字节数组转成16进制字符串 **/
    public static String byte2hex(byte[] b) { // 一个字节的数,
        StringBuffer sb = new StringBuffer(b.length * 2);
        String tmp = "";
        for (int n = 0; n < b.length; n++) {
            // 整数转成十六进制表示
            tmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString().toUpperCase(); // 转成大写
    }


    /** 将hex字符串转换成字节数组 **/
    private static byte[] hex2byte(String inputString) {
        if (inputString == null || inputString.length() < 2) {
            return new byte[0];
        }
        inputString = inputString.toLowerCase();
        int l = inputString.length() / 2;
        byte[] result = new byte[l];
        for (int i = 0; i < l; ++i) {
            String tmp = inputString.substring(2 * i, 2 * i + 2);
            result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
        }

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 165,893评论 24 701
  • 最近项目中考虑到用户账户数据的安全性问题,需要对用户账户相关信息进行加密解密。这里我们选择使用AES加解密,至于A...
    Jvaeyhcd阅读 12,397评论 13 11
  • DEMO 综述: 一行代码完成AES加密,加密模式 AES128 + ECB + NoPadding DEMO下载...
    iccpeng阅读 7,591评论 26 59
  • 带着众多期盼 和几多冷暖 悄悄而来 烟花和爆竹 是你轰轰烈烈地宣言 说给予世间繁华 赐与人们良善 我们信了 可是就...
    朴一阅读 79评论 0 0
  • 四 在这生死攸关的时候,冥天努力使自己静下心来,观察周围的情况,想要寻求一丝的生机……可是,与舱门之间的距离越来越...
    志桀阅读 132评论 0 0
  • 不要让你的任何情绪被别人牵着走,情绪的主人是自己
    你你你x阅读 39评论 0 1