In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you "what are the three commonly used encryption algorithms in Java?" the content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn what are the three commonly used encryption algorithms in Java.
Preface
There are several common encryption algorithms in programming, which are applied in different scenarios. Except for the information digest algorithm, all other encryption methods require a key.
Information summary algorithm
Symmetric encryption algorithm
Asymmetric encryption algorithm
Secret key
Key (also called key) refers to some secret information used to complete encryption, decryption, integrity verification and other cryptographic applications.
Key classification
Keys in encryption and decryption: share the same key in symmetric encryption, separate public key and private key in asymmetric encryption, public key encryption and private key decryption.
Key in message authentication code and digital signature: in message authentication code, the sender and receiver of the message use a shared key for authentication. In a digital signature, the signature uses the private key and the verification uses the public key.
Session key and master key: a key that is used only once per communication is called a session key (session key). Relative to the session key, the reused key is called the master key (master key).
Key and password
Passwords are generally generated by users, are readable, can be memorized and stored, and are often used in software management, while keys are used by software to implement encryption algorithms and do not need to be readable (but Base64 is performed to facilitate reading in programming). We can also use passwords to generate keys.
Key management
Generate a key: you can generate a key with a random number or a password.
Distribution key: you can share the key in advance, use the key distribution center, use public key cryptography, and use Diffie-Hellman key exchange.
Update key
Save key
Invalidate key
Key generation
The jce (Java Cryptography Extension) in jdk contains all the API related to encryption.
Generate the key of the symmetric encryption algorithm
Public static SecretKey generateKey (int keySize) {KeyGenerator keyGenerator; try {keyGenerator = KeyGenerator.getInstance ("AES"); keyGenerator.init (keySize); return keyGenerator.generateKey ();} catch (NoSuchAlgorithmException e) {/ / ignore return null;}}
Generate the key of symmetric asymmetric encryption algorithm
/ * * generate asymmetric key pair * * @ param keySize key size * @ param random specify random source. Default is JCAUtil.getSecureRandom () * @ return asymmetric key pair * @ throws NoSuchAlgorithmException NoSuchAlgorithm * / public static PPKeys genKeysRSA (int keySize, SecureRandom random) throws NoSuchAlgorithmException {KeyPairGenerator generator = KeyPairGenerator.getInstance ("RSA") If (null! = random) {generator.initialize (keySize, random);} else {generator.initialize (keySize);} KeyPair pair = generator.generateKeyPair (); PPKeys keys = new PPKeys (); PublicKey publicKey = pair.getPublic (); PrivateKey privateKey = pair.getPrivate (); keys.setPublicKey (Base64.getEncoder (). EncodeToString (publicKey.getEncoded () Keys.setPrivateKey (Base64.getEncoder () .encodeToString (privateKey.getEncoded (); return keys;}
Key agreement (Diffie-Hellman)
Key agreement is a protocol through which two or more parties establish the same shared key, and then the communication content is symmetrically encrypted and transmitted without the need to exchange keys.
The general process: each party generates a public-private key pair and distributes the public key to the other party. When each party gets a copy of the other party's public key, the shared key can be calculated offline.
KeyAgreement is provided in Java to implement key negotiation.
Alice and Bob initialize their key agreement object KeyAgreement with their private keys, respectively, and call the init () method
Then pass in the public key of each party of the communication to execute doPhase (Key key, boolean lastPhase)
Each party generates a shared key generateSecret ().
Public static void diffieHellman () throws Exception {AlgorithmParameterGenerator dhParams = AlgorithmParameterGenerator.getInstance ("DH"); dhParams.init (1024); KeyPairGenerator keyGen = KeyPairGenerator.getInstance ("DH"); keyGen.initialize (dhParams.generateParameters (). GetParameterSpec (DHParameterSpec.class), new SecureRandom ()); KeyAgreement aliceKeyAgree = KeyAgreement.getInstance ("DH"); KeyPair alicePair = keyGen.generateKeyPair (); KeyAgreement bobKeyAgree = KeyAgreement.getInstance ("DH") KeyPair bobPair = keyGen.generateKeyPair (); aliceKeyAgree.init (alicePair.getPrivate ()); bobKeyAgree.init (bobPair.getPrivate ()); aliceKeyAgree.doPhase (bobPair.getPublic (), true); bobKeyAgree.doPhase (alicePair.getPublic (), true); boolean agree = Base64.getEncoder (). EncodeToString (aliceKeyAgree.generateSecret ()). Equals (Base64.getEncoder (). EncodeToString (bobKeyAgree.generateSecret () System.out.println (agree);} Information Summary algorithm
The information digest algorithm is also called encryption hash algorithm, and the encryption process does not need a key. The common encryption hash algorithms are MD series and SHA series.
An ideal encrypted hash function should have the following characteristics:
When any information is passed in, the output is always of a fixed length
The message digest appears to be "random", so it is difficult to infer the value from the original information
The collision probability of a good hash function should be very low, that is, the probability of getting the same value after different information is introduced.
MD series
MD5 message digest algorithm (MD5 Message-Digest Algorithm), a widely used encrypted hash function, outputs a 128bit (16-byte) hash value (hash value). MD5 was originally designed as an encrypted hash function, but now it has been found to have a large number of vulnerabilities, so it is not recommended to be directly used for encryption, but it is still widely used in non-encrypted scenarios such as data integrity check and file integrity check.
Public static String md5 (String content) {try {MessageDigest digest = MessageDigest.getInstance ("MD5"); byte [] bytes = digest.digest (content.getBytes (StandardCharsets.UTF_8)); return Hex.encodeHexString (bytes);} catch (final NoSuchAlgorithmException e) {throw new IllegalArgumentException (e);}} SHA Series
Secure hash algorithm (Secure Hash Algorithm, abbreviated as SHA) is a family of encrypted hash functions, which is certified by FIPS (American Federal Information processing Standard). An algorithm that can calculate a fixed-length string corresponding to a digital message (also known as message digest). And if the messages entered are different, there is a high chance that they will correspond to different strings.
They contain SHA-0, SHA-1, SHA-2 and SHA-3 respectively. The output length of SHA-0 and SHA-1 is 160bit. SHA-2 contains SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224 and SHA-512/256. We usually use SHA-256.
Public static String sha256 (String content) {try {MessageDigest digest = MessageDigest.getInstance ("SHA-256); byte [] bytes = digest.digest (content.getBytes (StandardCharsets.UTF_8)); return Hex.encodeHexString (bytes);} catch (final NoSuchAlgorithmException e) {throw new IllegalArgumentException (e);}} symmetric encryption algorithm
Symmetric encryption algorithm, both parties hold the same key for encryption and decryption, the common symmetric encryption algorithm: DES 3DES AES128 AES192 AES256. Understanding symmetric encryption requires understanding the following concepts:
Block cipher mode: the plaintext is cut and encrypted, and then the ciphertext is spliced together. For example, in AES, plaintext data is cut into blocks of 16 bytes in size, and when the last block is less than 16 bytes, Padding mode is used to supplement it.
Padding: it has three modes PKCS5, PKCS7 and NOPADDING,PKCS5 to fill with missing bytes, such as missing 5 bytes to fill 5 digits and 5 PKCS7 missing bytes to fill with 0. If the data is exactly an integer multiple of 16, PKCS5 and PKCS7 will add another 16 bytes of data to distinguish between padding and valid data, and the NOPADDING schema does not need to be populated.
Initialization vector: the function of the initial vector IV is to make the encryption more secure and reliable, and the IV size corresponds to the block length in block cipher mode.
Encryption mode: the four encryption modes are: ECB (electronic codebook mode), CBC (password block link mode), CFB, OFB. ECB mode only uses plaintext and key to encrypt data, so there is no need for Padding in this mode, and the security is weak. CBC mode data is divided into blocks and uses the incoming IV to perform XOR operations in turn, so the security is relatively high, so CBC mode is generally chosen.
Encryption key: the key length varies with different encryption algorithms, for example, the default length of DES is 56 bits, the default length of 3DES is 168bits, and the default length of AES is 128bits. We generally generate the key according to the password, and the password length needs to meet the key length of the algorithm.
DES
DES is a typical algorithm in the field of symmetric encryption algorithms. Because the default length of the key is 56 bit, the length of the password needs to be greater than 8 byte,DESKeySpec and the first 8 byte should be used to make the key.
Public static String encryptDES (byte [] content, String password) {try {SecureRandom random = new SecureRandom (); DESKeySpec desKeySpec = new DESKeySpec (password.getBytes ()); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance ("DES"); SecretKey secretKey = secretKeyFactory.generateSecret (desKeySpec); Cipher cipher = Cipher.getInstance ("DES"); cipher.init (Cipher.ENCRYPT_MODE, secretKey, random) Return Base64.getEncoder () .encodeToString (cipher.doFinal (content));} catch (Exception e) {throw new RuntimeException (e);}} public static String decryptDES (String content, String password) throws Exception {SecureRandom random = new SecureRandom (); DESKeySpec desKeySpec = new DESKeySpec (password.getBytes ()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance ("DES"); SecretKey secretKey = keyFactory.generateSecret (desKeySpec) Cipher cipher = Cipher.getInstance ("DES"); cipher.init (Cipher.DECRYPT_MODE, secretKey, random); return new String (cipher.doFinal (Base64.getDecoder (). Decode (content));} 3DES
3DES (i.e. Triple DES). It is an enhancement of the DES algorithm, which uses three 56-bit keys to encrypt the data three times. It takes DES as the basic module and designs the packet encryption algorithm through the combined grouping method. It is more secure than the original DES,3DES. The default length of the key is 168 bit, and the password needs to be a random number and letter array of 8 byte with a password greater than 24 byte,IV.
Public static String encrypt3DESECB (String content, String key, String iv) {try {IvParameterSpec ivSpec = new IvParameterSpec (iv.getBytes (StandardCharsets.UTF_8)); DESedeKeySpec dks = new DESedeKeySpec (key.getBytes (StandardCharsets.UTF_8)); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance ("DESede"); SecretKey secretkey = keyFactory.generateSecret (dks); Cipher cipher = Cipher.getInstance ("DESede/CBC/PKCS5Padding") Cipher.init (Cipher.ENCRYPT_MODE, secretkey, ivSpec); return Base64.getEncoder () .encodeToString (cipher.doFinal (content.getBytes (StandardCharsets.UTF_8);} catch (Exception e) {throw new RuntimeException (e) }} public static String decrypt3DESECB (String content, String key, String iv) {try {IvParameterSpec ivSpec = new IvParameterSpec (iv.getBytes (StandardCharsets.UTF_8)); DESedeKeySpec dks = new DESedeKeySpec (key.getBytes (StandardCharsets.UTF_8)); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance ("DESede"); SecretKey secretkey = keyFactory.generateSecret (dks) Cipher cipher = Cipher.getInstance ("DESede/CBC/PKCS5Padding"); cipher.init (Cipher.DECRYPT_MODE, secretkey, ivSpec); return new String (cipher.doFinal (Base64.getDecoder (). Decode (content)), StandardCharsets.UTF_8);} catch (Exception e) {throw new RuntimeException (e);}} AES
AES Advanced data encryption Standard, which effectively protects against all known attacks against the DES algorithm, with a default key length of 128 bit and a choice of 192 bit,256 bit. AES-128 AES-192 AES-256
The default AES-128 uses PBEKeySpec to generate keys of a fixed size.
Public static String encryptAES128 (String plainText, String password, String salt) throws Exception {SecretKeyFactory factory = SecretKeyFactory.getInstance ("PBKDF2WithHmacSHA1"); byte [] saltBytes = salt.getBytes (StandardCharsets.UTF_8); / / AES-128 key length is 128bit PBEKeySpec spec = new PBEKeySpec (password.toCharArray (), saltBytes, 1000, 128); SecretKey secretKey = factory.generateSecret (spec) SecretKeySpec secret = new SecretKeySpec (secretKey.getEncoded (), "AES"); Cipher cipher = Cipher.getInstance ("AES/CBC/PKCS5Padding"); AlgorithmParameters params = cipher.getParameters (); IvParameterSpec iv = params.getParameterSpec (IvParameterSpec.class); cipher.init (Cipher.ENCRYPT_MODE, secret, iv); byte [] encryptedTextBytes = cipher.doFinal (plainText.getBytes (StandardCharsets.UTF_8)) String encodedText = Base64.getEncoder (). EncodeToString (encryptedTextBytes); String encodedIV = Base64.getEncoder (). EncodeToString (iv.getIV ()); String encodedSalt = Base64.getEncoder (). EncodeToString (saltBytes); return encodedSalt + "." + encodedIV + "." + encodedText;} public static String decryptAES128 (String encryptedText, String password) throws Exception {String [] fields = encryptedText.split ("\\.") Byte [] saltBytes = Base64.getDecoder (). Decode (fields [0]); byte [] ivBytes = Base64.getDecoder (). Decode (fields [1]); byte [] encryptedTextBytes = Base64.getDecoder (). Decode (fields [2]); SecretKeyFactory factory = SecretKeyFactory.getInstance ("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec (password.toCharArray (), saltBytes, 1000, 128) SecretKey secretKey = factory.generateSecret (spec); SecretKeySpec secret = new SecretKeySpec (secretKey.getEncoded (), "AES"); Cipher cipher = Cipher.getInstance ("AES/CBC/PKCS5Padding"); cipher.init (Cipher.DECRYPT_MODE, secret, new IvParameterSpec (ivBytes)); byte [] decryptedTextBytes; try {decryptedTextBytes = cipher.doFinal (encryptedTextBytes); return new String (decryptedTextBytes) } catch (IllegalBlockSizeException | BadPaddingException e) {throw new RuntimeException (e);}}
The following exceptions may occur when using AES-256:
Java.security.InvalidKeyException: Illegal key size
Unlimited strength encryption is enabled by default in JDK 1.8.0x161 and above:
Static {java.security.Security.setProperty ("crypto.policy", "unlimited");}
JDK versions prior to 1.8.0,161 require manual installation of jce policy files (download address)
Asymmetric encryption algorithm
Asymmetric encryption uses a pair of keys, with the public key used for encryption and the private key for decryption. With regard to key size, as of 2020, the largest known RSA key is the 829-bit RSA-250, and it is recommended to use at least 2048-bit key.
Public static String encrypt (byte [] publicKey, String plainText) {X509EncodedKeySpec keySpec = new X509EncodedKeySpec (publicKey); KeyFactory kf; try {kf = KeyFactory.getInstance ("RSA"); PublicKey publicKeySecret = kf.generatePublic (keySpec); Cipher cipher = Cipher.getInstance ("RSA/ECB/PKCS1Padding"); cipher.init (Cipher.ENCRYPT_MODE, publicKeySecret) Byte [] encryptedBytes = cipher.doFinal (plainText.getBytes ()); return new String (Base64.getEncoder (). Encode (encryptedBytes));} catch (Exception e) {log.error ("Rsa encrypt error", e); throw new RuntimeException (e);}} public static String decrypt (byte [] privateKey, String encryptedText) {PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec (privateKey) KeyFactory kf; try {kf = KeyFactory.getInstance ("RSA"); PrivateKey privateKeySecret = kf.generatePrivate (keySpec); Cipher cipher = Cipher.getInstance ("RSA/ECB/PKCS1Padding"); cipher.init (Cipher.DECRYPT_MODE, privateKeySecret); return new String (cipher.doFinal (Base64.getDecoder (). Decode (encryptedText)), StandardCharsets.UTF_8) } catch (Exception e) {log.error ("Rsa decrypt error", e); throw new RuntimeException (e);}} these are all the contents of the article "what are the three encryption algorithms commonly used in Java implementation". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.