Java 開発: データの暗号化と復号化を実装する方法、具体的なコード例が必要です
はじめに:
1. データ暗号化アルゴリズムの概要
2. Java が提供する暗号化および復号化 API
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class AESUtil { private static final String ALGORITHM = "AES"; private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding"; public static byte[] encrypt(byte[] data, byte[] key) throws Exception { SecretKeySpec secretKeySpec = new SecretKeySpec(key, ALGORITHM); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); return cipher.doFinal(data); } public static byte[] decrypt(byte[] data, byte[] key) throws Exception { SecretKeySpec secretKeySpec = new SecretKeySpec(key, ALGORITHM); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); return cipher.doFinal(data); } }
import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; public class RSAUtil { private static final String ALGORITHM = "RSA"; public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data); } public static byte[] decrypt(byte[] data, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(data); } public static byte[] sign(byte[] data, PrivateKey privateKey) throws Exception { Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(privateKey); signature.update(data); return signature.sign(); } public static boolean verify(byte[] data, byte[] sign, PublicKey publicKey) throws Exception { Signature signature = Signature.getInstance("SHA256withRSA"); signature.initVerify(publicKey); signature.update(data); return signature.verify(sign); } public static KeyPair generateKeyPair() throws Exception { KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGORITHM); generator.initialize(2048); return generator.generateKeyPair(); } }
結論:
以上がJava 開発: データの暗号化と復号化を実装する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。