当前位置:网站首页>Encryption algorithm - password security

Encryption algorithm - password security

2022-07-07 00:13:00 ljt-tiger

Password security

Abstract encryption

The summary is Hashi value , We use hash algorithms, such as MD5 The algorithm can get the hash value . Summary is just a hash value used to verify data integrity and uniqueness , No matter what the original data is , The resulting hash values are of fixed length . No matter what the original data is , The resulting hash values are of fixed length , In other words, the abstract is not the encrypted ciphertext of the original data , It's just an authentication token . So we can't decrypt the abstract to get the original data .

MD5 Information digest algorithm ( English :MD5 Message-Digest Algorithm), A widely used cryptographic hash function Count , I can produce one 128 position (16 byte ) Hash value (hash value), Used to ensure complete and consistent transmission of information .MD5 from American Cryptologist Ronald · Levister (Ronald Linn Rivest) Design , On 1992 Open in , To replace MD4 Algorithm . This set of The program of the algorithm is in RFC 1321 Regulated in standards .1996 Years later, the algorithm proved to be weak , Can be cracked , about Need highly secure data , Experts generally recommend using other algorithms , Such as SHA-2.2004 year , confirmed MD5 Algorithms can't prevent collisions (collision), So it doesn't apply to security certification , Such as SSL Public key authentication or digital signature . MD5 There is a flaw , As long as the text is the same , So the generated MD5 The code is the same , Then the attacker can hit the Library To crack the plaintext . Adding salt is to add specified characters to plaintext , Mainly used to confuse users 、 And add MD5 It's hard to crack the library , In this way, even if the library is cracked , I see , But plaintext is also confused , The data that really needs to be used also needs to be extracted from plaintext , Extraction range 、 length 、 The method of extraction is a mystery , This greatly increases the difficulty of brute force cracking , Make it almost impossible to crack .

Abstract encryption algorithm

  1. MD5 Algorithmic method (MD2 、MD4、MD5)
  2. SHA Algorithm (SHA1、SHA256、SHA384、 SHA512)
  3. HMAC Algorithm

characteristic

  1. Any data encryption , The length of the ciphertext obtained is fixed .
  2. The ciphertext cannot be decrypted ( Irreversible ).

attestation

Signature verification is actually signature verification ,MD5 Encryption algorithms are often used for signature security verification . doubt : What if the ciphertext is also changed and then transmitted ?

Code example

import org.apache.commons.codec.digest.DigestUtils;

public class MD5Util {
    

    /** * MD5 Method  * * @param text  Plaintext  * @return  Ciphertext  * @throws Exception */
    public static String md5(String text) throws Exception {
    
        // The encrypted string 
        String encode = DigestUtils.md5Hex(text);
        return encode;
    }

    /** * MD5 Method  * * @param text  Plaintext  * @param key  salt  * @return  Ciphertext  * @throws Exception */
    public static String md5(String text, String key) throws Exception {
    
        // The encrypted string 
        String encode = DigestUtils.md5Hex(text + key);
        return encode;
    }

    /** * MD5 Verification method  * * @param text  Plaintext  * @param key  secret key / salt  * @param md5  Ciphertext  * @return true/false * @throws Exception */
    public static boolean verify(String text, String key, String md5) throws Exception {
    
        // Verify against the incoming key 
        String md5Text = md5(text, key);
        return md5Text.equalsIgnoreCase(md5);
    }

    public static void main(String[] args) throws Exception {
    
        String test = "admin";
        String key = "tiger";
        String md5 = "bcf918bd662986b3bcab0f9a32a21e1d";
        String md5Str = md5(test, key);
        System.out.println(md5Str);
        boolean passOrNot = verify(test, key, md5);
        System.out.println(passOrNot);
    }
}

Base64

Base64 It's the most common transport on the network 8Bit One of the ways to encode bytecode ,Base64 It's based on 64 Printable Character to represent binary data .

Solve coding problems

Code example

import java.util.Base64;

public class Base64Util {
    

    /*** *  Ordinary decryption operation  * @param encodedText: Ciphertext  * @return */
    public static byte[] decode(String encodedText) {
    
        final Base64.Decoder decoder = Base64.getDecoder();
        return decoder.decode(encodedText);
    }

    /*** *  Ordinary encryption operation  * @param data * @return */
    public static String encode(byte[] data) {
    
        final Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(data);
    }

    /*** *  Decryption operation  * @param encodedText * @return */
    public static byte[] decodeURL(String encodedText) {
    
        final Base64.Decoder decoder = Base64.getUrlDecoder();
        return decoder.decode(encodedText);
    }

    /*** *  Encryption operation  * @param data * @return */
    public static String encodeURL(byte[] data) {
    
        final Base64.Encoder encoder = Base64.getUrlEncoder();
        return encoder.encodeToString(data);
    }

    public static void main(String[] args) throws Exception {
    
        String str = " Today's meal is really delicious ! Come back tomorrow !";

        //  encryption 
        String encode = encode(str.getBytes("UTF-8"));
        //  Decrypt 
        byte[] decode = decode(encode);
        //  Byte array  -》 character string 
        String text = new String(decode, "UTF-8");
        System.out.println(" Ciphertext :" + encode);
        System.out.println(" Plaintext :" + text);

        // URL
        //  encryption 
        String encodeURL = encodeURL(str.getBytes("UTF-8"));
        //  Decrypt 
        byte[] decodeURL = decodeURL(encodeURL);
        //  Byte array  -》 character string 
        String textURL = new String(decodeURL, "UTF-8");
        System.out.println(" Ciphertext :" + encodeURL);
        System.out.println(" Plaintext :" + textURL);
    }
}

Symmetric encryption AES

Typical symmetric encryption algorithms are AES、DES、3DES, but AES The security of encryption algorithm is higher than DES and 3DES, therefore AES It has become the main symmetric encryption algorithm .

AES Encryption algorithm is one of many symmetric encryption algorithms , Its full English name is Advanced Encryption Standard, Advanced Encryption Standard , It is used to replace the previous one DES Encryption algorithm . To understand AES Encryption process , It will involve AES Five key words of encryption , Namely : Block cipher system 、Padding、 The secret key 、 Initial vector IV And four encryption modes

Code example

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;

public class AESUtil {
    

    /** * AES encryption / Decrypt  * * @param buffer: Ciphertext / Plaintext  * @param secretKey: Secret key  * @param mode: encryption / Decryption mode  1  encryption  2  Decrypt  * @return */
    public static byte[] encryptAndDecrypt(byte[] buffer, String secretKey, Integer mode) throws Exception {
    
        // 1、 Load encryption and decryption algorithm processing object ( Inclusion algorithm 、 The secret key management )
        Security.addProvider(new BouncyCastleProvider());

        // 2、 Create secret keys according to different algorithms  1) Byte array of secret key  2) encryption algorithm 
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes("UTF-8"), "AES");

        // 3、 Set encryption mode ( Whether it's encryption or parsing , The pattern is the same )
        // 1)、AES/ECB/KPS7Padding  Set algorithm 
        // 2)、 Specify the algorithm library object 
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
        // 4、 Initialize encryption configuration 
        cipher.init(mode, secretKeySpec);
        // 5、 Perform encryption / Decrypt 
        return cipher.doFinal(buffer);
    }

    /*** *  Encryption and decryption test  *  secret key :128(16)、192(24)、256(32) */
    public static void main(String[] args) throws Exception {
    
        //  Plaintext 
        String plainText = "SpringCloud Alibaba";
        // 128bit 16 A key 
        String secretKey = "1234567890123456";
        //  take 128bit 16 A key  -》 256bit 32 A key 
        secretKey = MD5Util.md5(secretKey);
        System.out.println(" Plaintext :" + plainText);
        System.out.println(" secret key :" + secretKey);

        //  encryption 
        byte[] bytes = encryptAndDecrypt(plainText.getBytes("UTF-8"), secretKey, 1);
        //  code 
        String encodeStr = Base64Util.encode(bytes);
        System.out.println(" Ciphertext :" + encodeStr);

        // Decrypt  -> decode Base64-> Decrypt 
        byte[] decodeStr = encryptAndDecrypt(Base64Util.decode(encodeStr), secretKey, 2);
        System.out.println(" Decrypted data :" + new String(decodeStr, "UTF-8"));
    }
}

Wechat payment -Native

Interface document

https://pay.weixin.qq.com/wiki/doc/api/index.html

Process description

  1. The merchant background system generates orders according to the goods purchased by users .
  2. Users confirm payment and call WeChat payment 【 Unified order API】 Generate prepayment transaction ;
  3. Wechat payment system generates advance payment transaction sheet after receiving the request , And return to the QR code link of the trading session code_url.
  4. The back office system of the merchant is based on the returned code_url Generate qr code .
  5. Users open wechat “ scan ” Scan QR code , The wechat client sends the scanned content to the wechat payment system .
  6. Wechat payment system receives client request , After verifying the validity of the link, user payment is initiated , Ask the user to authorize .
  7. The user enters the password in the wechat client , After confirming the payment , Wechat client submit Authorization .
  8. Wechat payment system completes payment transaction according to user authorization .
  9. After the wechat payment system completes the payment transaction, it returns the transaction result to the wechat client , And send the transaction results through SMS 、 Wechat message prompts users . Wechat client shows payment transaction results page .
  10. Wechat payment system sends asynchronous messages to merchants to inform the payment result of background system . The merchant's back office system needs to reply the receiving situation , Inform wechat background system to no longer send the payment notice of this order .
  11. In the case of failure to receive payment advice , Merchant background system call 【 Query order API】.
  12. The merchant confirms that the order has been paid and then delivers the goods to the user .

Development steps

  1. It has been revised officially wxpay-sdk Source code , Change the modifier of the abstract method from the default to public, Then repackage to local or private servers

    import com.github.wxpay.sdk.IWXPayDomain;
    import com.github.wxpay.sdk.WXPayConfig;
    import com.github.wxpay.sdk.WXPayConstants;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    
    @Component
    public class WeixinPayConfig extends WXPayConfig {
          
    
        // Wechat payment information 
        @Value("${payconfig.weixin.appId}")
        private String appId;       // application ID
        @Value("${payconfig.weixin.mchID}")
        private String mchID;       // Merchant number 
        @Value("${payconfig.weixin.key}")
        private String key;         // Secret key 
        @Value("${payconfig.weixin.notifyUrl}")
        private String notifyUrl;   // token url 
        @Value("${payconfig.weixin.certPath}")
        private String certPath;    // The certificate path 
        // Certificate byte array 
        private byte[] certData;
    
        @Override
        public String getAppID() {
          
            return this.appId;
        }
    
        @Override
        public String getMchID() {
          
            return this.mchID;
        }
    
        @Override
        public String getKey() {
          
            return this.key;
        }
    
        /*** *  Obtain the content of merchant Certificate  * @return */
        @Override
        public InputStream getCertStream() {
          
            /**** *  Certificate of loading  */
            if (certData == null) {
          
                synchronized (WeixinPayConfig.class) {
          
                    try {
          
                        if (certData == null) {
          
                            File file = new File(certPath);
                            InputStream certStream = new FileInputStream(file);
                            this.certData = new byte[(int) file.length()];
                            certStream.read(this.certData);
                            certStream.close();
                        }
                    } catch (Exception e) {
          
                        e.printStackTrace();
                    }
                }
            }
            ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
            return certBis;
        }
    
        /*** *  obtain WXPayDomain,  It is used for automatic switching of multi domain name disaster recovery  * @return */
        @Override
        public IWXPayDomain getWXPayDomain() {
          
            //  This method needs to be implemented in this way ,  Otherwise, it cannot be initialized normally WXPay
            IWXPayDomain iwxPayDomain = new IWXPayDomain() {
          
                @Override
                public void report(String domain, long elapsedTimeMillis, Exception ex) {
          
    
                }
    
                @Override
                public DomainInfo getDomain(WXPayConfig config) {
          
    
                    return new DomainInfo(WXPayConstants.DOMAIN_API, true);
                }
            };
            return iwxPayDomain;
        }
    }
    
  2. Wechat payment \ The certificate and secret key configuration in the certificate and secret key are imported into mall-pay-service In Engineering , If it is php Development , use pem certificate , If it is java Development uses p12 certificate

  3. establish WXPay And give it to Spring Container management

    import com.github.wxpay.sdk.WXPay;
    import com.gupaoedu.vip.mall.pay.config.WeixinPayConfig;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.Bean;
    
    @SpringBootApplication
    @MapperScan(basePackages = {
          "com.tiger.mall.pay.mapper"})
    public class MallPayApplication {
          
    
        public static void main(String[] args) {
          
            SpringApplication.run(MallPayApplication.class, args);
        }
    
        /**** *  Wechat payment SDK object  * @param weixinPayConfig * @return * @throws Exception */
        @Bean
        public WXPay wxPay(WeixinPayConfig weixinPayConfig) throws Exception {
          
            return new WXPay(weixinPayConfig);
        }
    }
    

Wechat refund

原网站

版权声明
本文为[ljt-tiger]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131017274215.html