注册登录请求中RSA加密,PHP服务器和Android客户端实现

本文介绍了如何在HTTP请求中使用RSA加密保护敏感信息,如密码。在PHP服务器端,通过openssl命令生成RSA密钥,封装加密解密方法,并在注册、登录接口中应用。Android客户端则获取公钥进行加密。文章还分享了测试接口及客户端遇到的Base64编码和RSA分组填充问题的解决方案。
摘要由CSDN通过智能技术生成

前言

客户端利用Http协议进行注册和登录等操作时,如果不做特殊处理,请求中携带的密码等敏感信息是明文传输的,有可能会被截获。解决这个问题最好的方法当然是使用Https协议,但是Https协议需要像权威机构申请证书才能保证足够的安全性,在没有证书的情况下,可以考虑自己来实现加密解密处理。

我们现在的场景只考虑在Http请求中加密,Http响应中没有敏感信息,暂时不考虑加密。首先考虑下对称加密的方式,这种方式客户端和服务器保存了一份相同的密钥,客户端加密和服务器解密是都需要用到,但是客户端程序有被破解的可能性,密钥有可能被泄露,攻击者拿到密钥再去截获请求报文,就可以解密出敏感信息来。因此最后选择了非对称加密RSA算法,客户端使用公钥加密,服务端再利用私钥解密,这样客户端只需要保存公钥了,即使泄露了也没法用来加密。可以实现敏感信息和密钥都处于相对安全的状态。
Github地址:
服务器:https://github.com/zhongchenyu/jokes-laravel
Android: https://github.com/zhongchenyu/jokes

PHP服务端实现

1. 生成密钥

可以利用 openssl 命令来生成RSA的密钥,一般linux系统都预装了。另外项目用的是 Laravel 框架,可以利用框架生成命令,将创建密钥的命令封装起来。
首先在项目路径下执行命令 php artisan make:command GenerateRSAKey
然后编辑GenerateRSAKey类的handle函数:

 public function handle()
    {
   
        //
      $keyDir = 'sec';
      if(!is_dir($keyDir)) mkdir($keyDir);
      echo getcwd() . "\n";
      chdir($keyDir);
      echo getcwd() . "\n";
      //生成原始 RSA私钥文件 rsa_private_key.pem
      shell_exec('openssl genrsa -out rsa_private_key.pem 1024');
      //将原始 RSA私钥转换为 pkcs8格式
      shell_exec('openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out private_key.pem');
      //生成RSA公钥 rsa_public_key.pem
      shell_exec('openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem');
      chdir('..');
      echo getcwd() . "\n";
      return;
    }

执行命令后就会在项目的 sec 目录下生成公钥和私钥文件了。

2. 加密解密方法封装

创建一个RSAUtils类来专门处理加密和解密,实际上服务器只需要利用私钥解密就够了,不过为了以后的可扩展性,把所有的加解密方法都先写了:

class RsaUtils {
   

  public static function enPublic($data)
  {
   
    $path = base_path();
    $publicKey = openssl_get_publickey(file_get_contents($path.'/sec/rsa_public_key.pem'));
    openssl_public_encrypt($data,$encrypted,$publicKey);
    $base64Encoded = base64_encode($encrypted);
    return $base64Encoded;
  }

  public static function dePrivate($data)
  {
   
    $path = base_path();
    $privateKey = openssl_get_privatekey(file_get_contents($path.'/sec/rsa_private_key.pem'));
    openssl_private_decrypt(base64_decode($data), $decrypted, $privateKey);

    return $decrypted;
  }

  public static function enPrivate($data) {
   
    $path = base_path();
    $privateKey = openssl_get_privatekey(file_get_contents(
RSA封装类 ,完整的RSA加密和解密 public class RSAUtilEncrypt { public static final String KEY_ALGORTHM = "RSA";// public static final String KEY_ALGORTHM_RSA_ECB_PKCS1PADDING = "RSA/ECB/PKCS1Padding"; public static String RSA_PUBLIC_KEY = "rsa_public_key"; public static String RSA_PRIVATE_KEY = "rsa_private_key"; private int KeySize = 1024; private Map keyMap; private static String RSA = "RSA"; private static PublicKey publickey; public RSAUtilEncrypt(int KeySize,String publickey) { this.KeySize = KeySize; try { this.publickey=generatePublicKeyByString(publickey); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private RSAPublicKey generatePublicKeyByString(String publicKeyStr) throws Exception { try { BASE64Decoder base64Decoder = new BASE64Decoder(); byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return (RSAPublicKey) keyFactory.generatePublic(keySpec); } catch (NoSuchAlgorithmException e) { throw new Exception("No Algorthm,Checked by cemung!"); } catch (InvalidKeySpecException e) { throw new Exception("InvalidKeySpec!"); } catch (IOException e) { throw new Exception("Io exception!"); } catch (NullPointerException e) { throw new Exception("Illegle pointer reference!"); } } // Encypt public byte[] RSAEncrypt(byte[] data, RSAPublicKey publickey) throws Exception { Cipher cipher = Cipher.getInstance(KEY_ALGORTHM_RSA_ECB_PKCS1PADDING); cipher.init(Cipher.ENCRYPT_MODE, this.publickey); byte[] cipherbytes = cipher.doFinal(data); return cipherbytes; } // Encypt public byte[] RSAEncrypt(byte[] data) throws Exception { Cipher cipher = Cipher.getInstance(KEY_ALGORTHM_RSA_ECB_PKCS1PADDING); cipher.init(Cipher.ENCRYPT_MODE, this.publickey); byte[] cipherbytes = cipher.doFinal(data); return cipherbytes; } // Get Public key with format byte[] public byte[] getPublicKeyByte() { RSAPublicKey pubkey = (RSAPublicKey) keyMap.get(RSA_PUBLIC_KEY); return pubkey.getEncoded(); } public static byte[] decryptBASE64(String key) throws Exception { return (new BASE64Decoder()).decodeBuffer(key); } public static String encryptBASE64(byte[] key) throws Exception { return (new BASE64Encoder()).encodeBuffer(key); } public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception { byte[] keyBytes = decryptBASE64(key); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(data); } public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception { byte[] keyBytes = decryptBASE64(key); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data); } public static byte[] decryptByPublicKey(byte[] data, String key) throws Exception { byte[] keyBytes = decryptBASE64(key); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicKey); return cipher.doFinal(data); } 使用方法 private RSAUtilEncrypt rsa = new RSAUtilEncrypt(1024, publikey); /* * 给信息加密,获取密文 */ public String getCiphertext(String str_encrode) { try { byte[] estr = rsa.RSAEncrypt(str_encrode.getBytes()); // 密文 String ciphertext = Base64.encodeToString(estr, Base64.DEFAULT); return ciphertext; } catch (Exception e) { e.printStackTrace(); } return null; } 有疑问的留言
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值