我正在创建一个脚本来解密加密的 .XML 文件。我有公钥和私钥,并且我使用私钥进行解密。我有密文,想将其转换为纯文本。
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class Cipher {
private static final byte[] pub = Base64.getDecoder().decode("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCMU67g985laZbW42c9MBX9zV6OBZMM1c/PyBQSdQfG+dMsQpwhxwkIYpmChZeU7VUewQMwqIh+Y3KKz32npMgMUbqNS+8X1aAPqqDIL66vXXpj+VR/8P4bTSz3Qd1tl3UUqFaqOvBbOXOcpXThnOF5TR95O0xxhWoDElb5UhpmwIDAQAB");
private static final byte[] pri = Base64.getDecoder().decode("MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIIxTruD3zmVpltbjZz0wFf3NXo4FkwzVz8/IFBJ1B8b50yxCnCHHCQhimYKFl5TtVR7BAzCoiH5jcorPfaekyAxRuo1L7xfVoA+qoMgvrq9demP5VH/w/htNLPdB3W2XdRSoVqo68Fs5c5yldOGc4XlNH3k7THGFagMSVvlSGmbAgMBAAECgYAtJnxve2RGzCdNN4r9C8RIvWrGX/0boBJ51KKYNYJi54Jnjl5YeALCZP9iM81eGRmhmqfk5PrlXW5W1ng+tu++k08wEwlGdBcE4TlFC+BdwSMiplarsrDbVAOcAaOuv0KgZKu5iqb0dgHW1+fKo/Xb+c1X6AG6sTNGd49X1feFgQJBAMXXOY2wind1gKXEdK8LvMXdq6JJi9dFxC6DlWytcW8UR1gKA369lyvL7s6zEhq+sNL05bXJbzJ4PWTtnY2nO1kCQQCodyGJNHpLBwN4HqoYP/6UvCcdK9XpdJWwJrYIjKdXwwWNg0QrhsCXLKbaDoUYcJ7UVB6/NKuQ2Cvn5rLWsNITAkEAjkDSFkpRVdH8XbUjvVWwN4nLRpahYXm9tUBR6eHQhXFMV0Zj+vaxwwEQxjlGFEr288i5fvvG48BHTNH6DoeniQJAWGFXeLHNTrs5OLVtqxc3qjQjmQw8RyPgu+8zJL0VtdccfKdXBjbFpwnH5zIi5TWAPgh7sPgi4fRm5FyFilhtfQJAMP3aMAcRjowXmreQqvVSCBQ2DIhxCAdibRFb1tBZP+wMNK56ghxVJyyozFHKGRxAhQdyaS3dFpXroTHD2pISIQ==");
public static String decrypt(String encryptedText) {
try {
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(pri);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(javax.crypto.Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(encryptedText)));
} catch (Exception e) {
e.printStackTrace();
return "Failed";
}
}
public static void main(String[] args) {
String encryptedText = loadFullContentFromFile("encrypted.xml");
if (encryptedText != null) {
System.out.println("Encrypted: " + encryptedText);
System.out.println("Decrypted: " + Cipher.decrypt(encryptedText));
} else {
System.out.println("Failed to read the encrypted content from file.");
}
}
private static String loadFullContentFromFile(String fileName) {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return content.toString();
}
}
我不完全确定我还需要什么才能成功解密它。我可能忽略了什么吗?我还有包含加密/解密类的 .jar 文件,但我不确定它们是否应该与这些 .xml 文件一起使用。我感谢任何帮助!
我的 .XML 内容如下所示:
ßn
lf.O¸Ñ�Eq sNMF[\ØùÚO“€¥œfÁd÷X,ÀÇœ˘Σyì”ËîºÖÿaøòíÖÇr3°aˆ
5dé!ˆç]Èú:@ÏÚÈ\Øåò#£¢Úûm∞ÖÎ CÉ>)Iû\À€πÉmÑ+Êôà}........ 等等
然后将其编码为base64格式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Exception: Data must not be longer than 128 bytes
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:349)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:423)
at javax.crypto.Cipher.doFinal(Cipher.java:2168)
at Cipher.decrypt(Cipher.java:37)
at Cipher.main(Cipher.java:48)
我还做了什么?
我不确定执行解密需要什么步骤。
我找到了这个加密器.class
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
public final class Encrypter {
private Key encryptionKey;
private Cipher encoder;
public Encrypter(Key key) throws GeneralSecurityException {
if (key == null) {
throw new IllegalArgumentException("Specify a public key");
} else {
this.encryptionKey = key;
this.encoder = Cipher.getInstance(key.getAlgorithm(), EncryptionFactory.PROVIDER);
this.encoder.init(1, this.encryptionKey);
}
}
public byte[] encrypt(String message) throws IllegalArgumentException, GeneralSecurityException, UnsupportedEncodingException {
if (message == null) {
throw new IllegalArgumentException("Message must be non null");
} else {
byte[] plain = message.getBytes("UTF8");
return this.encoder.doFinal(plain);
}
}
public byte[] encrypt(byte[] message) throws IllegalArgumentException, GeneralSecurityException {
if (message == null) {
throw new IllegalArgumentException("Message must be non null");
} else {
return this.encoder.doFinal(message);
}
}
public OutputStream getEncryptedStream(OutputStream os) {
return new CipherOutputStream(os, this.encoder);
}
}
还有这个 encrypterFactory 类:
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public final class EncryptionFactory {
private static SecureRandom random = null;
public static final Provider PROVIDER = new BouncyCastleProvider();
public static void init() {
Security.addProvider(PROVIDER);
}
public static String sign(PrivateKey key, String message) throws GeneralSecurityException, UnsupportedEncodingException {
Signature sig = Signature.getInstance("MD5withRSA", PROVIDER);
sig.initSign(key);
sig.update(message.getBytes("utf-8"));
return new String(Base64.encode(sig.sign()), "UTF-8");
}
public static boolean verifySignature(PublicKey key, String message, String signedMessage) throws GeneralSecurityException, UnsupportedEncodingException {
if (!Base64.isBase64(signedMessage)) {
throw new GeneralSecurityException("Not b64 message");
} else {
Signature sig = Signature.getInstance("MD5withRSA", PROVIDER);
sig.initVerify(key);
sig.update(message.getBytes("utf-8"));
return sig.verify(Base64.decode(signedMessage.getBytes("UTF-8")));
}
}
public static Encrypter getEncrypter(Key key) throws GeneralSecurityException {
return new Encrypter(key);
}
public static Decrypter getDecrypter(Key key) throws GeneralSecurityException {
return new Decrypter(key);
}
public static PublicKey getPublicKeyFromString(String keyString) throws GeneralSecurityException, UnsupportedEncodingException {
if (!Base64.isBase64(keyString)) {
throw new GeneralSecurityException("Not b64");
} else {
X509EncodedKeySpec keyspec = new X509EncodedKeySpec(Base64.decode(keyString.getBytes("UTF8")));
KeyFactory factory = KeyFactory.getInstance("RSA", PROVIDER);
return factory.generatePublic(keyspec);
}
}
public static PrivateKey getPrivateKeyFromString(String keyString) throws GeneralSecurityException, UnsupportedEncodingException {
if (!Base64.isBase64(keyString)) {
throw new GeneralSecurityException("Not b64 data");
} else {
PKCS8EncodedKeySpec keyspec = new PKCS8EncodedKeySpec(Base64.decode(keyString.getBytes("UTF8")));
KeyFactory factory = KeyFactory.getInstance("RSA", PROVIDER);
PrivateKey key = factory.generatePrivate(keyspec);
return key;
}
}
public static String getStringFromPrivateKey(PrivateKey key) throws GeneralSecurityException, UnsupportedEncodingException {
return new String(Base64.encode(key.getEncoded()), "UTF8");
}
public static String getStringFromPublicKey(PublicKey key) throws GeneralSecurityException, UnsupportedEncodingException {
return new String(Base64.encode(key.getEncoded()), "UTF8");
}
public static SecretKey getSecretKeyFromString(String keyString) throws GeneralSecurityException, UnsupportedEncodingException {
try {
if (!Base64.isBase64(keyString)) {
throw new GeneralSecurityException("Not b64 message");
}
} catch (IndexOutOfBoundsException var3) {
throw new GeneralSecurityException("Not b64 message");
}
byte[] encodedBytes = keyString.getBytes("UTF8");
byte[] keyBytes = Base64.decode(encodedBytes);
if (keyBytes == null) {
throw new GeneralSecurityException("Failed to decode b64 message");
} else {
return getSecretKey(keyBytes);
}
}
public static SecretKey getSecretKey(byte[] keyBytes) throws GeneralSecurityException {
DESedeKeySpec keySpec = new DESedeKeySpec(keyBytes);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede", PROVIDER);
return factory.generateSecret(keySpec);
}
public static String getNextRandomString() throws GeneralSecurityException, UnsupportedEncodingException {
SecretKey key = generateSecretKey();
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede", PROVIDER);
DESedeKeySpec spec = (DESedeKeySpec)factory.getKeySpec(key, DESedeKeySpec.class);
byte[] keyBytes = spec.getKey();
byte[] escapedBytes = Base64.encode(keyBytes);
String s = new String(escapedBytes, "UTF8");
return s;
}
public static SecretKey generateSecretKey() throws NoSuchAlgorithmException, NoSuchProviderException {
if (random == null) {
random = SecureRandom.getInstance("SHA1PRNG", "SUN");
random.setSeed((new Date()).getTime());
}
KeyGenerator generator = KeyGenerator.getInstance("DESede", PROVIDER);
generator.init(168, random);
SecretKey key = generator.generateKey();
return key;
}
static {
init();
}
}
我希望这能提供更多背景信息