电话加密方法
更新时间:2024-05-16
获取加密密钥
当您购买智能外呼产品后,可以登录智能外呼,在智能外呼的「系统管理」-> 「对接配置」中可以获取到密钥用于加密
加密代码示例
Java代码示例
package baidu.com;
import okhttp3.*;
import org.json.JSONObject;
import java.io.IOException;
class Demo {
public static final String CHARSET = "utf-8";
private static final String AES = "AES";
private static final String ALGORITHM = "AES/ECB/PKCS5Padding";
public static void main(String[] args) throws IOException {
// 电话 密钥
encryptAES("15532271587", "MRvNJ2R9HAAuImT3");
}
@SneakyThrows
/**
* 加密
* plainText 电话号码
* password 密钥
*/
private static String encryptAES(String plainText, String password) {
String cipherText = plainText;
if (StringUtils.isNotBlank(plainText) && StringUtils.isNotBlank(password)) {
byte[] cipherBytes = encryptAES(plainText.getBytes(CHARSET), password.getBytes(CHARSET));
cipherText = byte2HexText(cipherBytes);
}
return cipherText;
}
private static byte[] encryptAES(byte[] plainBytes, byte[] password) {
byte[] cipherBytes = null;
try {
if (plainBytes != null && password != null) {
SecretKeySpec skeySpec = new SecretKeySpec(password, AES);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
cipherBytes = cipher.doFinal(plainBytes);
}
} catch (Exception e) {
// throw new BusinessException(e.getMessage(), e);
throw ExceptionUtil.make(CommonErrorStatusCode.AES_DECRYPT_ENCRYPT_ERROR);
}
return cipherBytes;
}
private static String byte2HexText(byte[] bytes) {
String hexText = "";
String strTmp = "";
for (int n = 0; n < bytes.length; n++) {
strTmp = (Integer.toHexString(bytes[n] & 0XFF));
if (strTmp.length() == 1) {
hexText = hexText + "0" + strTmp;
} else {
hexText = hexText + strTmp;
}
}
return hexText.toUpperCase();
}
}
python代码示例
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import binascii
class Demo:
CHARSET = "utf-8"
AES_MODE = AES.MODE_ECB
ALGORITHM = "AES/ECB/PKCS5Padding"
@staticmethod
def main():
# 电话号码,密钥
encrypted = Demo.encryptAES("15532271587", "MRvNJ2R9HAAuImT3")
print(encrypted)
@staticmethod
def encryptAES(plain_text, password):
cipher_text = plain_text
if plain_text and password:
cipher_bytes = Demo._encryptAES(bytes(plain_text, Demo.CHARSET),
bytes(password, Demo.CHARSET))
cipher_text = Demo.byte2HexText(cipher_bytes)
return cipher_text
@staticmethod
def _encryptAES(plain_bytes, password):
try:
if plain_bytes and password:
skey_spec = pad(password, AES.block_size)
cipher = AES.new(skey_spec, Demo.AES_MODE)
cipher_bytes = cipher.encrypt(pad(plain_bytes, AES.block_size))
return cipher_bytes
except Exception as e:
# 在这里处理异常,例如打印日志
# 在实际应用中,您可能需要根据需求抛出具体异常或执行其他异常处理逻辑
raise Exception("AES encryption error") from e
@staticmethod
def byte2HexText(bytes_array):
hex_text = binascii.hexlify(bytes_array).decode().upper()
return hex_text
# 执行主方法
if __name__ == "__main__":
Demo.main()