Clé secrète vers chaîne
Nous allons convertir la SecretKey en un tableau d'octets. Ensuite, nous allons convertir le tableau d'octets en String en utilisant l'encodage Base64 :
public static String convertSecretKeyToString(SecretKey secretKey) throws NoSuchAlgorithmException {
byte[] rawData = secretKey.getEncoded();
String encodedKey = Base64.getEncoder().encodeToString(rawData);
return encodedKey;
}
Chaîne à SecretKey
Nous allons convertir la clé String encodée en un tableau d'octets à l'aide du décodage Base64. Ensuite, en utilisant SecretKeySpecs , nous convertirons le tableau d'octets en SecretKey :
public static SecretKey convertStringToSecretKeyto(String encodedKey) {
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
return originalKey;
}