java手机号码加密解密
时间: 2024-05-09 10:11:35 浏览: 134
java 加密 解密
在Java中,可以使用不同的加密算法对手机号码加密和解密。常见的加密算法包括对称加密算法和非对称加密算法。
对称加密算法使用相同的密钥进行加密和解密,常见的对称加密算法有DES、AES等。以下是一个使用AES算法对手机号码进行加密和解密的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class PhoneEncryptorDecryptor {
private static final String AES_ALGORITHM = "AES";
private static final String AES_KEY = "0123456789abcdef"; // 密钥,必须是16位
public static String encrypt(String phoneNumber) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(AES_KEY.getBytes(), AES_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(phoneNumber.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedPhoneNumber) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(AES_KEY.getBytes(), AES_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedPhoneNumber);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
try {
String phoneNumber = "13812345678";
String encryptedPhoneNumber = PhoneEncryptorDecryptor.encrypt(phoneNumber);
System.out.println("加密后的手机号码:" + encryptedPhoneNumber);
String decryptedPhoneNumber = PhoneEncryptorDecryptor.decrypt(encryptedPhoneNumber);
System.out.println("解密后的手机号码:" + decryptedPhoneNumber);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文