Java中的非对称加密密码学

密码学是研究和实践不同技术以保护通信免受第三方干扰的学科。它用于网络安全。我们试图开发方法和实践来保护敏感数据。密码学的唯一目标是保护数据免受攻击者的侵害。非对称加密也被称为公钥/私钥加密。私钥如其名,将保持私有,而公钥可以分发。加密是两个密钥之间的数学关联,一个用于加密,另一个用于解密。例如,如果有两个密钥“A1”和“A2”,那么如果密钥“A1”用于加密,“A2”用于解密,反之亦然。

我们使用RSA算法进行非对称加密,首先我们会生成一对密钥(公钥、私钥)。

非对称加密在Java中的密码学

To generate asymmetric key following steps can be followed −

  • 首先,我们使用SecureRandom类生成公钥和私钥。它用于生成随机数。

  • By using RSA algorithm to generate keys. This class will provide getInstance() method which is used to pass a string variable which signify the key generation algorithm and it returns to key generator object.

  • 使用2048位密钥大小初始化密钥生成器对象,并传递随机数。

  • Now, the secret key is generated and we want to look at the key we can convert it into hexbinary format by using DatatypeConvertor.

现在实施上述方法 −

Syntax

// Java program to create a // asymmetric key package java_cryptography; import java.security.KeyPair; import java.security .KeyPairGenerator; import java.security .SecureRandom; import javax.xml.bind .DatatypeConverter; // Class to create an asymmetric key public class Asymmetric { private static final String RSA = "RSA"; // Generating public and private keys // using RSA algorithm. public static KeyPair generateRSAKkeyPair() throws Exception { SecureRandom secureRandom = new SecureRandom(); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA); keyPairGenerator.initialize( 2048, secureRandom); return keyPairGenerator .generateKeyPair(); } // Driver code public static void main(String args[]) throws Exception { KeyPair keypair = generateRSAKkeyPair(); System.out.println( "Public Key is: " + DatatypeConverter.printHexBinary( keypair.getPublic().getEncoded())); System.out.println( "Private Key is: " + DatatypeConverter.printHexBinary( keypair.getPrivate().getEncoded())); } } 登录后复制