是否有一些Java等价的Convert.FromBase64String
将指定的字符串转换为等效的8位无符号整数数组,该字符串将二进制数据编码为基数为64的数字。
我试过了:
对任何建议都会感激不尽!
答案 0 :(得分:3)
一般情况下,如果标准Java库没有您需要的东西,那么很可能是Apache Commons框架。在这种情况下,您需要 decodeBase64
中的 commons.codec.binary.Base64
方法。
答案 1 :(得分:0)
通过Convert.FromBase64String
中的AES
加密中的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);
}
}