c#等效于Java AES解密代码

时间:2019-06-21 08:06:22

标签: java c# .net

有人知道如何将代码转换为C#吗?

这是定义键的不变用法

private static final String KEY_ALGORITHM = "AES";
private static final String CHAR_SET = "UTF-8";
private static final Integer SECRET_KEY_LENGTH = 256;
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

解密时使用的功能

// function to call when doing decrypt
public static String decrypt(String encryptContent, String password) {
    if (StringUtils.isAnyEmpty(encryptContent, password)) {
        LOGGER.error("AES decryption params is null");
        return null;
    }
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
        byte[] result = cipher.doFinal(Base64.decodeBase64(encryptContent));
        return new String(result, CHAR_SET);
    } catch (Exception e) {
    }
    return null;
}

使用此功能生成AES密钥

// this is to generate the key
private static SecretKeySpec getSecretKey(final String password) throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyGenerator kgen = KeyGenerator.getInstance(KEY_ALGORITHM);
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");
    secureRandom.setSeed(password.getBytes());
    kgen.init(SECRET_KEY_LENGTH, secureRandom);
    SecretKey secretKey = kgen.generateKey();

    return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
}

0 个答案:

没有答案