用JAVA写一个 任意字符串加密后 长度不超过20位 并可以进行解密 代码
以下是一个简单的Java代码示例,可以将任意字符串进行加密,并确保加密后的字符串长度不超过20位,并可以进行解密:
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class StringEncryption {
private static final String ALGORITHM = "AES";
private static final String KEY = "mysecretpassword";
public static String encrypt(String value) throws Exception {
Key key = generateKey();
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedByteValue = cipher.doFinal(value.getBytes("utf-8"));
String encryptedValue64 = Base64.getEncoder().encodeToString(encryptedByteValue);
return encryptedValue64.substring(0, 20);
}
public static String decrypt(String value) throws Exception {
Key key = generateKey();
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedValue64 = Base64.getDecoder().decode(value);
byte[] decryptedByteValue = cipher.doFinal(decryptedValue64);
String decryptedValue = new String(decryptedByteValue, "utf-8");
return decryptedValue;
}
private static Key generateKey() throws Exception {
byte[] keyValue = KEY.getBytes("utf-8");
Key key = new SecretKeySpec(keyValue, ALGORITHM);
return key;
}
public static void main(String[] args) throws Exception {
String originalString = "This is a secret message.";
String encryptedString = encrypt(originalString);
String decryptedString = decrypt(encryptedString);
System.out.println("Original String: " + originalString);
System.out.println("Encrypted String: " + encryptedString);
System.out.println("Decrypted String: " + decryptedString);
}
}
在此示例中,我们使用AES算法对字符串进行加密和解密。加密密钥为“mysecretpassword”,在实际应用中应该更改为更安全的密钥。
在加密过程中,我们将加密后的字节数组转换为Base64字符串,并从中提取长度不超过20位的子字符串。在解密过程中,我们将Base64字符串解码为字节数组,然后使用相同的密钥和算法对其进行解密。
请注意,此示例仅用于演示目的,应该根据实际应用场景进行修改和增强。
原文地址: https://www.cveoy.top/t/topic/bdkR 著作权归作者所有。请勿转载和采集!