springBoot解密手机号,返给前端158****1724格式如何实现
时间: 2023-12-04 07:39:21 浏览: 154
微信小程序前端解密获取手机号
以下是使用Spring Boot解密手机号并返回给前端的代码示例:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PhoneController {
@PostMapping("/decryptPhone")
public String decryptPhone(@RequestBody PhoneInfo phoneInfo) throws Exception {
String encryptedData = phoneInfo.getEncryptedData();
String sessionKey = phoneInfo.getSessionKey();
String iv = phoneInfo.getIv();
byte[] encryptedByte = Base64.decodeBase64(encryptedData);
byte[] sessionKeyByte = Base64.decodeBase64(sessionKey);
byte[] ivByte = Base64.decodeBase64(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKeyByte, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivByte);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedByte = cipher.doFinal(encryptedByte);
String decryptedData = new String(decryptedByte, "UTF-8");
JSONObject jsonObject = JSONObject.parseObject(decryptedData);
String phoneNumber = jsonObject.getString("phoneNumber");
String purePhoneNumber = jsonObject.getString("purePhoneNumber");
String countryCode = jsonObject.getString("countryCode");
String maskedPhoneNumber = purePhoneNumber.substring(0, 3) + "****" + purePhoneNumber.substring(7);
return maskedPhoneNumber;
}
}
```
上述代码中,我们使用了Java的AES加密算法和Base64编码解码工具类来解密用户的手机号。解密后,我们从解密后的JSON对象中获取手机号码,并将其格式化为158****1724的形式,最后将其返回给前端。
阅读全文