4

是否有一些 Java 等效的Convert.FromBase64String

将指定的字符串(将二进制数据编码为 base-64 位)转换为等效的 8 位无符号整数数组。

我试过了:

将不胜感激任何建议!

4

2 回答 2

6

一般而言,如果标准 Java 库没有您需要的东西,Apache Commons 框架就有。在这种情况下,您需要decodeBase64来自 的方法commons.codec.binary.Base64

于 2010-02-16T17:39:05.167 回答
1

密钥和初始向量使用Convert.FromBase64StringinAES加密转换C#

在java中,您可以使用DatatypeConverter.parseBase64Binary(string)方法。为了使用它导入import javax.xml.bind.*;

这是示例程序

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.*;

class AESEncryption {

    private static final String key = "type your key here.(base64)";
    private static final String initVector = "type your initial vector here.(base64)";

    static byte[] encodedKey = DatatypeConverter.parseBase64Binary(key);
    static byte[] encodedIV = DatatypeConverter.parseBase64Binary(initVector);

    public static String encrypt(final String value) {
        try {
            IvParameterSpec iv = new IvParameterSpec(encodedIV);
            SecretKeySpec skeySpec = new SecretKeySpec(encodedKey, "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());

            return Base64.getEncoder().encodeToString(encrypted);

        } catch (final Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String decrypt(final String encrypted) {
        try {
            IvParameterSpec iv = new IvParameterSpec(encodedIV);
            SecretKeySpec skeySpec = new SecretKeySpec(encodedKey, "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted));

            return new String(original);

        } catch (final Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static void main(final String[] args) {

        String originalString = "Here is your text to be encrypted.";
        System.out.println("Original String to encrypt - " + originalString);

        String encryptedString = encrypt(originalString);
        System.out.println("Encrypted String - " + encryptedString);

        String decryptedString = decrypt(encryptedString);
        System.out.println("After decryption - " + decryptedString);
    }
}
于 2020-04-03T11:43:39.077 回答