您的位置:首页 > 移动开发 > Android开发

openssl加密 适用于 php+Java/Android

2016-01-20 00:58 561 查看
APP开发,为了提高数据传输的安全性,针对敏感信息进行AES对称加密

客户端 app 加密

需要 jar

http://bouncycastle.org/latest_releases.html,我使用的是bcprov-jdk16-146.jar

/**
* @author xiaoxin
*/

import java.io.IOException;
import java.lang.reflect.Method;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

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

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import sun.misc.BASE64Decoder;

public class AESUtil {

private static final String ALGORITHM      = "AES";
private static final String TRANSFORMATION = "AES/CBC/PKCS7Padding";
private static final String SECRET_KEY     = "key-32-char-long";
private static final String SECRET_IV      = "111111111111111"; // 16位随机串

public static void main(String[] args) throws Exception{
String sf = "test";
String encrypt = encodeBase64(getCipher(Cipher.ENCRYPT_MODE).doFinal(sf.getBytes()));
// encrypt 打印的值 直接在在PHP代码中解密
System.out.println(encrypt);
}

/***
* encode by Base64
*/
public static String encodeBase64(byte[]input) throws Exception{
Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method mainMethod= clazz.getMethod("encode", byte[].class);
mainMethod.setAccessible(true);
Object retObj=mainMethod.invoke(null, new Object[]{input});
return (String)retObj;
}
/***
* decode by Base64
*/
public static byte[] decodeBase64(String input) throws Exception{
Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method mainMethod= clazz.getMethod("decode", String.class);
mainMethod.setAccessible(true);
Object retObj=mainMethod.invoke(null, input);
return (byte[])retObj;
}

private static Cipher getCipher(int ENCRYPT_MODE) throws Exception {

Cipher cipher = Cipher.getInstance(TRANSFORMATION ,new BouncyCastleProvider());
cipher.init(ENCRYPT_MODE, new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM), new IvParameterSpec(SECRET_IV.getBytes()));

return cipher;
}

}


服务端 php 解密

首先 安装openssl扩展

<?php

$key = "key-32-char-long";
$cipher = "AES-256-CBC"; // 加密算法 填充模式 加密模式
$iv = "111111111111111"; // 16位随机串--与android端加密串参数保持一致,在此复用
$encrypt = "encrypt"; // android 端输出的信息
$toDectypt = openssl_decrypt($encrypt, $cipher, $key , 0 , $iv);

var_dump($toDectypt); // 正确输出 test
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  openssl 加密