Java是一種廣泛使用的編程語言,可以用于各種應用和領域,包括加密和安全。RSA是一種非對稱加密算法,用于加密和解密數據,并保護它們免受非法訪問和攻擊。同時,PFX和CER是兩種常用的數字證書格式,用于驗證和證明所需的加密和認證信息。
RSA算法: import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.util.Base64; public class RSA { public static void main(String[] args) throws Exception { String message = "Hello, World!"; KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(privateKey); signature.update(message.getBytes("UTF-8")); byte[] sign = signature.sign(); System.out.println(Base64.getEncoder().encodeToString(sign)); signature.initVerify(publicKey); signature.update(message.getBytes("UTF-8")); boolean result = signature.verify(sign); System.out.println(result); } } PFX格式: import java.io.FileInputStream; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.Certificate; public class PFX { public static void main(String[] args) throws Exception { String password = "password"; String path = "example.pfx"; KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(new FileInputStream(path), password.toCharArray()); String alias = keyStore.aliases().nextElement(); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray()); Certificate certificate = keyStore.getCertificate(alias); byte[] encoded = certificate.getEncoded(); } } CER格式: import java.io.FileInputStream; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; public class CER { public static void main(String[] args) throws Exception { String path = "example.cer"; FileInputStream fis = new FileInputStream(path); CertificateFactory certificateFactory = CertificateFactory.getInstance("X509"); Certificate certificate = certificateFactory.generateCertificate(fis); byte[] encoded = certificate.getEncoded(); } }
在Java中,RSA,PFX和CER都被廣泛應用于加密和安全領域,可以通過相應的API和庫輕松實現。無論是加密和解密數據,還是驗證和證明加密和認證信息,Java提供了全方位的支持和便捷的操作。