百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

非对称加密算法之Java RSA算法应用 附可用工具类

toyiye 2024-09-04 20:25 7 浏览 0 评论

  RSA算法简介


  RSA公开密钥密码体制是一种使用不同的加密密钥与解密密钥,“由已知加密密钥推导出解密密钥在计算上是不可行的”密码体制。

  在公开密钥密码体制中,加密密钥(即公开密钥)PK是公开信息,而解密密钥(即秘密密钥)SK是需要保密的。加密算法E和解密算法D也都是公开的。虽然解密密钥SK是由公开密钥PK决定的,但却不能根据PK计算出SK。

  RSA允许你选择公钥的大小。512位的密钥被视为不安全的;768位的密钥不用担心受到除了国家安全管理(NSA)外的其他事物的危害;1024位的密钥几乎是安全的。

  关于RSA概念性的内容不做过多介绍,大家可以自行百度。

  Maven 依赖

  工具类对于加密后使用Base64进行编码,所以需要依赖Apache Commons Codec。

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

  工具类实现

  RSAUtil提供了针对文本内容、字节数组内容的加解密实现,RSAUtil工具类可以直接复制使用,代码如下:

package com.arhorchin.securitit.enordecryption.rsa;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
/**
 * @author Securitit.
 * @note RSA加密算法实现.
 */
public class RSAUtil {
    /**
     * logger.
     */
    private static Logger logger = Logger.getLogger(RSAUtil.class);
    /**
     * 数据编码.
     */
    private static final String CHARSET_UTF8 = "UTF-8";
    /**
     * 加密算法RSA.
     */
    public static final String RSA_NAME = "RSA";
    /**
     * 获取公钥的key.
     */
    public static final String PUBLIC_KEY = "RSAPublicKey";
    /**
     * 获取私钥的key.
     */
    public static final String PRIVATE_KEY = "RSAPrivateKey";
    /**
     * RSA最大加密明文大小.
     */
    public static final int MAX_ENCRYPT_BLOCK = 117;
    /**
     * RSA最大解密密文大小.
     */
    public static final int MAX_DECRYPT_BLOCK = 128;
    /**
     * RSA密钥长度必须是64的倍数,在512~65536之间。默认是1024.
     */
    public static final int KEY_SIZE = 1024;
    /**
     * 生成RSA算法的密钥对.
     * @return 返回存储密钥对的Map.
     * @throws Exception 可能的异常.
     */
    public static Map<String, String> generateDesKey() throws Exception {
        Map<String, String> keysMap = null;
        KeyPair keyPair = null;
        RSAPublicKey publicKey = null;
        RSAPrivateKey privateKey = null;
        KeyPairGenerator keyPairGenerator = null;
        // Key存储Map.
        keysMap = new HashMap<String, String>(2);
        // 生成RSA秘钥对.
        keyPairGenerator = KeyPairGenerator.getInstance(RSA_NAME);
        keyPairGenerator.initialize(KEY_SIZE);
        keyPair = keyPairGenerator.generateKeyPair();
        publicKey = (RSAPublicKey) keyPair.getPublic();
        privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 放置到存储Map.
        keysMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded()));
        keysMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded()));
        return keysMap;
    }
    /**
     * RAS基于Private密钥加密.
     * @param plainText 原文内容.
     * @param privateKey 私钥.
     * @return 加密后内容.
     * @throws Exception 可能的异常.
     */
    public static String encodeTextByPrivateKey(String plainText, String privateKey) throws Exception {
        byte[] privateKeyBytes = null;
        byte[] cipherBytes = null;
        try {
            privateKeyBytes = Base64.decodeBase64(privateKey);
            cipherBytes = encodeByRsa(plainText.getBytes(CHARSET_UTF8), privateKeyBytes, true);
            return Base64.encodeBase64String(cipherBytes);
        } catch (Exception ex) {
            logger.error("RSAUtil.encodeTextByPrivateKey.", ex);
            return "";
        }
    }
    /**
     * RAS基于Private密钥解密.
     * @param cipherText 密文内容.
     * @param privateKey 私钥.
     * @return 解密后内容.
     * @throws Exception 可能的异常.
     */
    public static String decodeTextByPrivateKey(String cipherText, String privateKey) throws Exception {
        byte[] privateKeyBytes = null;
        byte[] plainBytes = null;
        try {
            privateKeyBytes = Base64.decodeBase64(privateKey);
            plainBytes = decodeByRsa(Base64.decodeBase64(cipherText), privateKeyBytes, true);
            return new String(plainBytes, CHARSET_UTF8);
        } catch (Exception ex) {
            logger.error("RSAUtil.decodeTextByPrivateKey.", ex);
            return "";
        }
    }
    /**
     * RAS基于Public密钥加密.
     * @param plainText 原文内容.
     * @param PublicKey 公钥.
     * @return 加密后内容.
     * @throws Exception 可能的异常.
     */
    public static String encodeTextByPublicKey(String plainText, String publicKey) throws Exception {
        byte[] publicKeyBytes = null;
        byte[] cipherBytes = null;
        try {
            publicKeyBytes = Base64.decodeBase64(publicKey);
            cipherBytes = encodeByRsa(plainText.getBytes(CHARSET_UTF8), publicKeyBytes, false);
            return Base64.encodeBase64String(cipherBytes);
        } catch (Exception ex) {
            logger.error("RSAUtil.encodeTextByPublicKey.", ex);
            return "";
        }
    }
    /**
     * RAS基于Public密钥解密.
     * @param cipherText 密文内容.
     * @param publicKey 公钥.
     * @return 解密后内容.
     * @throws Exception 可能的异常.
     */
    public static String decodeTextByPublicKey(String cipherText, String publicKey) throws Exception {
        byte[] publicKeyBytes = null;
        byte[] plainBytes = null;
        try {
            publicKeyBytes = Base64.decodeBase64(publicKey);
            plainBytes = decodeByRsa(Base64.decodeBase64(cipherText), publicKeyBytes, false);
            return new String(plainBytes, CHARSET_UTF8);
        } catch (Exception ex) {
            logger.error("RSAUtil.decodeTextByPublicKey.", ex);
            return "";
        }
    }
    /**
     * RAS基于Private密钥加密.
     * @param plainBytes 原文内容.
     * @param privateKey 私钥.
     * @return 加密后内容.
     * @throws Exception 可能的异常.
     */
    public static byte[] encodeBytesByPrivateKey(byte[] plainBytes, String privateKey) throws Exception {
        byte[] privateKeyBytes = null;
        byte[] cipherBytes = null;
        try {
            privateKeyBytes = Base64.decodeBase64(privateKey);
            cipherBytes = encodeByRsa(plainBytes, privateKeyBytes, true);
            return cipherBytes;
        } catch (Exception ex) {
            logger.error("RSAUtil.encodeTextByPrivateKey.", ex);
            return new byte[0];
        }
    }
    /**
     * RAS基于Private密钥解密.
     * @param cipherBytes 密文内容.
     * @param privateKey 私钥.
     * @return 解密后内容.
     * @throws Exception 可能的异常.
     */
    public static byte[] decodeBytesByPrivateKey(byte[] cipherBytes, String privateKey) throws Exception {
        byte[] privateKeyBytes = null;
        byte[] plainBytes = null;
        try {
            privateKeyBytes = Base64.decodeBase64(privateKey);
            plainBytes = decodeByRsa(cipherBytes, privateKeyBytes, true);
            return plainBytes;
        } catch (Exception ex) {
            logger.error("RSAUtil.decodeTextByPrivateKey.", ex);
            return new byte[0];
        }
    }
    /**
     * RAS基于Public密钥加密.
     * @param plainBytes 原文内容.
     * @param PublicKey 公钥.
     * @return 加密后内容.
     * @throws Exception 可能的异常.
     */
    public static byte[] encodeBytesByPublicKey(byte[] plainBytes, String publicKey) throws Exception {
        byte[] publicKeyBytes = null;
        byte[] cipherBytes = null;
        try {
            publicKeyBytes = Base64.decodeBase64(publicKey);
            cipherBytes = encodeByRsa(plainBytes, publicKeyBytes, false);
            return cipherBytes;
        } catch (Exception ex) {
            logger.error("RSAUtil.encodeTextByPublicKey.", ex);
            return new byte[0];
        }
    }
    /**
     * RAS基于Public密钥解密.
     * @param cipherBytes 密文内容.
     * @param publicKey 公钥.
     * @return 解密后内容.
     * @throws Exception 可能的异常.
     */
    public static byte[] decodeBytesByPublicKey(byte[] cipherBytes, String publicKey) throws Exception {
        byte[] publicKeyBytes = null;
        byte[] plainBytes = null;
        try {
            publicKeyBytes = Base64.decodeBase64(publicKey);
            plainBytes = decodeByRsa(cipherBytes, publicKeyBytes, false);
            return plainBytes;
        } catch (Exception ex) {
            logger.error("RSAUtil.decodeTextByPublicKey.", ex);
            return new byte[0];
        }
    }
    /**
     * 利用RSA进行加密,支持公钥和私钥.
     * @param plainBytes 待加密原文内容.
     * @param rsaKeyBytes RSA密钥.
     * @param isPrivateKey 是否私钥.
     * @return 加密结果.
     * @throws Exception 可能的异常.
     */
    public static byte[] encodeByRsa(byte[] plainBytes, byte[] rsaKeyBytes, boolean isPrivateKey) throws Exception {
        KeyFactory keyFactory = null;
        Key rsaKeyObj = null;
        Cipher cipher = null;
        PKCS8EncodedKeySpec pkcs8KeySpec = null;
        X509EncodedKeySpec x509KeySpec = null;
        int plainLength = plainBytes.length;
        byte[] cipherCacheBytes = null;
        int cipherPartTotal = 0;
        ByteArrayOutputStream baos = null;
        baos = new ByteArrayOutputStream();
        // 生成密钥算法对象.
        keyFactory = KeyFactory.getInstance(RSA_NAME);
        // 处理加密使用的Key.
        if (isPrivateKey) {
            pkcs8KeySpec = new PKCS8EncodedKeySpec(rsaKeyBytes);
            rsaKeyObj = keyFactory.generatePrivate(pkcs8KeySpec);
        } else {
            x509KeySpec = new X509EncodedKeySpec(rsaKeyBytes);
            rsaKeyObj = keyFactory.generatePublic(x509KeySpec);
        }
        cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        // 初始化算法密钥.
        cipher.init(Cipher.ENCRYPT_MODE, rsaKeyObj);
        // 计算分组,对报文进行分段加密.
        plainLength = plainBytes.length;
        cipherPartTotal = (int) Math.ceil((float) plainLength / MAX_ENCRYPT_BLOCK);
        for (int partIndex = 0; partIndex < cipherPartTotal; partIndex++) {
            if (partIndex == cipherPartTotal - 1) {
                cipherCacheBytes = cipher.doFinal(plainBytes, MAX_ENCRYPT_BLOCK * partIndex, plainLength);
            } else {
                cipherCacheBytes = cipher.doFinal(plainBytes, MAX_ENCRYPT_BLOCK * partIndex,
                        MAX_ENCRYPT_BLOCK * (partIndex + 1));
            }
            baos.write(cipherCacheBytes, 0, cipherCacheBytes.length);
        }
        return baos.toByteArray();
    }
    /**
     * 利用RSA进行解密,支持公钥和私钥.
     * @param cipherBytes 待解密原文内容.
     * @param rsaKeyBytes RSA密钥.
     * @param isPrivateKey 是否私钥.
     * @return 加密结果.
     * @throws Exception 可能的异常.
     */
    public static byte[] decodeByRsa(byte[] cipherBytes, byte[] rsaKeyBytes, boolean isPrivateKey) throws Exception {
        KeyFactory keyFactory = null;
        Key rsaKeyObj = null;
        Cipher cipher = null;
        PKCS8EncodedKeySpec pkcs8KeySpec = null;
        X509EncodedKeySpec x509KeySpec = null;
        int plainLength = cipherBytes.length;
        byte[] cipherCacheBytes = null;
        int cipherPartTotal = 0;
        ByteArrayOutputStream baos = null;
        baos = new ByteArrayOutputStream();
        // 生成密钥算法对象.
        keyFactory = KeyFactory.getInstance(RSA_NAME);
        // 处理加密使用的Key.
        if (isPrivateKey) {
            pkcs8KeySpec = new PKCS8EncodedKeySpec(rsaKeyBytes);
            rsaKeyObj = keyFactory.generatePrivate(pkcs8KeySpec);
        } else {
            x509KeySpec = new X509EncodedKeySpec(rsaKeyBytes);
            rsaKeyObj = keyFactory.generatePublic(x509KeySpec);
        }
        cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        // 初始化算法密钥.
        cipher.init(Cipher.DECRYPT_MODE, rsaKeyObj);
        // 计算分组,对报文进行分段解密.
        plainLength = cipherBytes.length;
        cipherPartTotal = (int) ((float) plainLength / MAX_ENCRYPT_BLOCK);
        for (int partIndex = 0; partIndex < cipherPartTotal; partIndex++) {
            if (partIndex == cipherPartTotal - 1) {
                cipherCacheBytes = cipher.doFinal(cipherBytes, MAX_ENCRYPT_BLOCK * partIndex, plainLength);
            } else {
                cipherCacheBytes = cipher.doFinal(cipherBytes, MAX_ENCRYPT_BLOCK * partIndex,
                        MAX_ENCRYPT_BLOCK * (partIndex + 1));
            }
            baos.write(cipherCacheBytes, 0, cipherCacheBytes.length);
        }
        return baos.toByteArray();
    }
}

  工具类测试

package com.arhorchin.securitit.enordecryption.rsa;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
/**
 * @author Securitit.
 * @note RSAUtil测试类.
 */
public class RSAUtilTester {
    public static void main(String[] args) throws Exception {
        Map<String, String> keyMap = null;
        String publicKey = null;
        String privateKey = null;
        String plaintext = null;
        String ciphertext = null;
        byte[] cipherBytes = null;
        String dePlaintext = null;
        byte[] dePlainBytes = null;
        System.out.println("----------------------- 获取RSA密钥对 -------------------------");
        keyMap = RSAUtil.generateDesKey();
        publicKey = keyMap.get(RSAUtil.PUBLIC_KEY);
        privateKey = keyMap.get(RSAUtil.PRIVATE_KEY);
        System.out.println("公钥:" + publicKey);
        System.out.println("私钥:" + privateKey);
        System.out.println();
        System.out.println("----------------------- 字符串 公钥加密、私钥解密 -------------------------");
        plaintext = "这是一段数据原文-公钥加密的原文.";
        // 公钥进行加密示例.
        ciphertext = RSAUtil.encodeTextByPublicKey(plaintext, publicKey);
        System.out.println("公钥加密密文:" + ciphertext);
        // 私钥进行解密示例.
        dePlaintext = RSAUtil.decodeTextByPrivateKey(ciphertext, privateKey);
        System.out.println("私钥解密明文:" + dePlaintext);
        System.out.println();
        System.out.println("----------------------- 字符串 私钥加密、公钥解密 -------------------------");
        plaintext = "这是一段数据原文-私钥加密的原文.";
        // 私钥进行加密示例.
        ciphertext = RSAUtil.encodeTextByPrivateKey(plaintext, privateKey);
        System.out.println("私钥加密密文:" + ciphertext);
        // 公钥进行解密示例.
        dePlaintext = RSAUtil.decodeTextByPublicKey(ciphertext, publicKey);
        System.out.println("公钥解密明文:" + dePlaintext);
        System.out.println("----------------------- 字节数组 公钥加密、私钥解密 -------------------------");
        plaintext = "这是一段数据原文-公钥加密的原文.";
        // 公钥进行加密示例.
        cipherBytes = RSAUtil.encodeBytesByPublicKey(plaintext.getBytes("UTF-8"), publicKey);
        ciphertext = Base64.encodeBase64String(cipherBytes);
        System.out.println("公钥加密密文:" + ciphertext);
        // 私钥进行解密示例.
        dePlainBytes = RSAUtil.decodeBytesByPrivateKey(Base64.decodeBase64(ciphertext), privateKey);
        dePlaintext = new String(dePlainBytes, "UTF-8");
        System.out.println("私钥解密明文:" + dePlaintext);
        System.out.println();
        System.out.println("----------------------- 字节数组 私钥加密、公钥解密 -------------------------");
        plaintext = "这是一段数据原文-私钥加密的原文.";
        // 私钥进行加密示例.
        cipherBytes = RSAUtil.encodeBytesByPrivateKey(plaintext.getBytes("UTF-8"), privateKey);
        ciphertext = Base64.encodeBase64String(cipherBytes);
        System.out.println("私钥加密密文:" + ciphertext);
        // 公钥进行解密示例.
        dePlainBytes = RSAUtil.decodeBytesByPublicKey(Base64.decodeBase64(ciphertext), publicKey);
        dePlaintext = new String(dePlainBytes, "UTF-8");
        System.out.println("公钥解密明文:" + dePlaintext);
    }
}

  控制台输出

  查看Console中的控制台内容,明文和解密后明文对比,可以确认RSAUtil可以正常工作,控制台如下图:

----------------------- 获取RSA密钥对 -------------------------
公钥:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQAJFIhf5nNviRgssUabOvM8iqcrXCYmPBX9s37y9z41THaF3B+7Au1+jhGl482LFBRivVl6yeBpfHGT/uNyO9ld9oBo5qbIx7hEApkxHtfd6P4i2zWxlDyqcSxy5QyrZclH7wci8UFzrbQBKD/wKFu80Tft3Neu03HnbD70zOjQIDAQAB
私钥:MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJAAkUiF/mc2+JGCyxRps68zyKpytcJiY8Ff2zfvL3PjVMdoXcH7sC7X6OEaXjzYsUFGK9WXrJ4Gl8cZP+43I72V32gGjmpsjHuEQCmTEe193o/iLbNbGUPKpxLHLlDKtlyUfvByLxQXOttAEoP/AoW7zRN+3c167TcedsPvTM6NAgMBAAECgYAkscBTtrFJI9zbV3TgUr8S2iM8K9bdHa1FzWNTMYPqB/fGiHW7xKL0jNgu5EU3RBCHDZaF6wx1iECM34ZG8Y4Nk4evaSvqxSpSyAEMWchln2K4KrAaHfvYBjy0MYz7/YXWdtYunaufDrFqBkCcB1Skfz6QUf9ryYOhPQnat+FggQJBAMZiXdClpmkzeZq7D+4ZU3VIw+cO/mPTjy1teKnqM6SNV+BuhdPy4aYy7yYGHdIlWBPx3O4P4d90L7sQ2E6BXJUCQQC50vY1PrvHq0vTQ6tKhDr+tTK6LkToOC9W8bNnYXYVBlAdB5CDtjUaoKcf9LIWSfU+1YRuGkte5nArXjK6yrQZAkA+4xnINWquOKIY2amwGZkqObnYOhmMPZlKlkRE4LgkNqYfwAluabT8QXMsA45aenoUQHx/fstkUWl8DFf1cu6NAkEApJQPs8DIF2PDWG2KfAj5JzXco8DvDq0UYHDZcCqFpsFcmxlkCQOLrPW0jzztrYf7SZdaHxnyvy5hEkfvrjhxoQJBAJAFJX26aaVXou1Dd5/Z5rqwi3Kc+d+HWM/54SBqxljKf0No1f0UW/MP4D5vFpXvnfI5a62NF+89Y4R3IejQIzg=
----------------------- 字符串 公钥加密、私钥解密 -------------------------
公钥加密密文:f0T4XxT6L2/t10/hhFD1NWriDgdAQNe9wLp34+Dkyn+w568GUDb8WZPbelmLoARzfz0DXI5fRFyRmbb9Zq5zqrxW1i/Ea0bs7cNnDQ23okPUNyIRdguMneAlrfi+WQgFJWXu9GUSMmFWMVgCAdtAX2I4YPXSmKuS3JX7fIslDxw=
私钥解密明文:这是一段数据原文-公钥加密的原文.
----------------------- 字符串 私钥加密、公钥解密 -------------------------
私钥加密密文:BYI5K56BuSuXp/0Thxc94Tck4W92+bDkeJEIP2qxjyQFst2RB+J6YXWp6LQBCMqEpwwEWgMDBv+U42V9nVMDCTDmugx2oqzT2xys7mMOIhQQsrccISCDzF/lk+CfrxY0hdEc4PJGrqn7vvCoKslBuJEgTL0uUxQirlJ6EVXc76g=
公钥解密明文:这是一段数据原文-私钥加密的原文.
----------------------- 字节数组 公钥加密、私钥解密 -------------------------
公钥加密密文:hvITbYLCnOhrCWDX/DgJNbuJTQWXXFzdPK6bVgep1MH99UyLO7nGKhqNViuVxuTqdVn1nh28Oz1ueA/PMNtiWCXHRUpVYgU957jfvoL17Eugyn9If81EJMpelBP9tdAb7lZJJiECkoUZpQvGImTNIYtONZA9dXGrakT15xO5m+I=
私钥解密明文:这是一段数据原文-公钥加密的原文.
----------------------- 字节数组 私钥加密、公钥解密 -------------------------
私钥加密密文:BYI5K56BuSuXp/0Thxc94Tck4W92+bDkeJEIP2qxjyQFst2RB+J6YXWp6LQBCMqEpwwEWgMDBv+U42V9nVMDCTDmugx2oqzT2xys7mMOIhQQsrccISCDzF/lk+CfrxY0hdEc4PJGrqn7vvCoKslBuJEgTL0uUxQirlJ6EVXc76g=
公钥解密明文:这是一段数据原文-私钥加密的原文.

  总结

  算法实现都很类似,本文只是对算法实现做了整理,在Maven依赖引入的情况下,RSAUtil已经做了简单测试,可以直接使用。

相关推荐

# Python 3 # Python 3字典Dictionary(1)

Python3字典字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中,格式如...

Python第八课:数据类型中的字典及其函数与方法

Python3字典字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值...

Python中字典详解(python 中字典)

字典是Python中使用键进行索引的重要数据结构。它们是无序的项序列(键值对),这意味着顺序不被保留。键是不可变的。与列表一样,字典的值可以保存异构数据,即整数、浮点、字符串、NaN、布尔值、列表、数...

Python3.9又更新了:dict内置新功能,正式版十月见面

机器之心报道参与:一鸣、JaminPython3.8的热乎劲还没过去,Python就又双叒叕要更新了。近日,3.9版本的第四个alpha版已经开源。从文档中,我们可以看到官方透露的对dic...

Python3 基本数据类型详解(python三种基本数据类型)

文章来源:加米谷大数据Python中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。在Python中,变量就是变量,它没有类型,我们所说的"类型"是变...

一文掌握Python的字典(python字典用法大全)

字典是Python中最强大、最灵活的内置数据结构之一。它们允许存储键值对,从而实现高效的数据检索、操作和组织。本文深入探讨了字典,涵盖了它们的创建、操作和高级用法,以帮助中级Python开发...

超级完整|Python字典详解(python字典的方法或操作)

一、字典概述01字典的格式Python字典是一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型。字典的每个键值key=>value对用冒号:分割,每个对之间用逗号,...

Python3.9版本新特性:字典合并操作的详细解读

处于测试阶段的Python3.9版本中有一个新特性:我们在使用Python字典时,将能够编写出更可读、更紧凑的代码啦!Python版本你现在使用哪种版本的Python?3.7分?3.5分?还是2.7...

python 自学,字典3(一些例子)(python字典有哪些基本操作)

例子11;如何批量复制字典里的内容2;如何批量修改字典的内容3;如何批量修改字典里某些指定的内容...

Python3.9中的字典合并和更新,几乎影响了所有Python程序员

全文共2837字,预计学习时长9分钟Python3.9正在积极开发,并计划于今年10月发布。2月26日,开发团队发布了alpha4版本。该版本引入了新的合并(|)和更新(|=)运算符,这个新特性几乎...

Python3大字典:《Python3自学速查手册.pdf》限时下载中

最近有人会想了,2022了,想学Python晚不晚,学习python有前途吗?IT行业行业薪资高,发展前景好,是很多求职群里严重的香饽饽,而要进入这个高薪行业,也不是那么轻而易举的,拿信工专业的大学生...

python学习——字典(python字典基本操作)

字典Python的字典数据类型是基于hash散列算法实现的,采用键值对(key:value)的形式,根据key的值计算value的地址,具有非常快的查取和插入速度。但它是无序的,包含的元素个数不限,值...

324页清华教授撰写【Python 3 菜鸟查询手册】火了,小白入门字典

如何入门学习python...

Python3.9中的字典合并和更新,了解一下

全文共2837字,预计学习时长9分钟Python3.9正在积极开发,并计划于今年10月发布。2月26日,开发团队发布了alpha4版本。该版本引入了新的合并(|)和更新(|=)运算符,这个新特性几乎...

python3基础之字典(python中字典的基本操作)

字典和列表一样,也是python内置的一种数据结构。字典的结构如下图:列表用中括号[]把元素包起来,而字典是用大括号{}把元素包起来,只不过字典的每一个元素都包含键和值两部分。键和值是一一对应的...

取消回复欢迎 发表评论:

请填写验证码