代码之家  ›  专栏  ›  技术社区  ›  Md. Masum Billah

字符串到密钥的转换/反之亦然

  •  0
  • Md. Masum Billah  · 技术社区  · 6 年前

    key = KeyGenerator.getInstance(ALGO_SECRET_KEY_GENERATOR).generateKey();

    我想把这把钥匙送到另一个地方。如果我使用intent,我认为这需要从Secret key转换成一个字符串。有人能告诉我有关密钥转换的情况吗。。。

    0 回复  |  直到 5 年前
        1
  •  2
  •   Ashish Rana    6 年前

    只需遵循以下步骤。

    `SecretKey secretKey = KeyGenerator.getInstance("ALGO_SECRET_KEY_GENERATOR").generateKey();
    // Crate base64 string 
    String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());`
    

    从字符串到键

    `// decode base64 string
    byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
    // rebuild key using SecretKeySpec
    SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "ALGO_SECRET_KEY_GENERATOR"); `
    

    可从api版本8获得

    `SecretKey secretKey = null;
                    try {
                        secretKey = KeyGenerator.getInstance("AES").generateKey();
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    }
    
                    byte encoded[] = secretKey.getEncoded();
                    String str = android.util.Base64.encodeToString(encoded , 0);
    
                    byte decoded[] = android.util.Base64.decode(str , 0);
    
                    SecretKey originalKey = new SecretKeySpec(decoded, 0, decoded.length, "AES");'