经典脱敏算法—泛化类截断法

​截断方法:对数值、字符型,截断不需要的,保留关键数据位(156893...—留156)

import time # 做性能测试
import pandas as pd
import random
import xlwt  # 先安装pip install

#随机替换函数
def replace_str_1(str, start, end):
    if len(str) >= (start + end):
        return str[:start] + ''.join(random.sample('0123456789', end)) + str[start+end:]
    else:
        return str
def replace_str(str, start, end):
    if len(str) > (start + end):
        return str[:start] + ''.join(random.sample('******************', end)) + str[start + end:]
    else:
        return str

#打开需要加密文件
data_test = pd.read_excel('....data/date_test.xlsx')
print(data_test)
#在原基础上不增新列,将total_bill改为object类型
data_test['card_t'] = data_test['card_t'].astype((str))

#需要改变的列
card_t_list = data_test['card_t']
#print(len(card_t_list))
#加密开始时间
time_start_enc = time.time()
#遍历替换
for i in range(len(card_t_list)):
    card = card_t_list[i]
    card = replace_str(card, 4, 10)     #这是核心的那一点,调用替换
    card = replace_str_1(card, 16,2)
    card_t_list[i] = card
time_end_enc = time.time()
print("加密耗时s:",time_end_enc-time_start_enc)
print(data_test)

# 导出为xls文件
data_test.to_excel('....data/date_test_success.xlsx', index=False)
'''
加密耗时s: 0.008274316787719727
'''

原文件:

脱敏后:

### 数据脱敏算法概述 数据脱敏旨在通过特定的方和技术来保护敏感信息,防止未经授权的数据访问。这通常涉及对原始数据进行转换或修改,使得即使泄露也不会暴露真实的信息[^1]。 #### 工作原理 数据脱敏的核心在于创建一套规则集用于指导如何处理不同型的数据项。这些规则可以基于简单的字符替换、更复杂的加密技术或是其他形式的变换操作。例如,在某些情况下,可能仅需简单地用星号(*)或其他符号覆盖部分个人信息;而在另一些场景下,则会采用高级别的加密手段确保安全性[^2]。 对于每种型的输入值都有相应的输出模式——即所谓的“掩码”。此过程不仅限于静态文本字符串,还包括日期时间戳、地理位置坐标等多种格式化后的数值型变量。重要的是要保持业务逻辑的一致性和连贯性,以便经过处理之后的数据仍然能够满足分析需求而不影响决策支持系统的正常运作[^3]。 #### 常见的应用场景 - **金融行业**:信用卡号码、银行账户余额等财务资料; - **医疗保健领域**:患者姓名、病历记录中的诊断结果和个人健康状况描述; - **电子商务平台**:用户的收货地址详情以及联系方式; - **社交网络服务提供商**:个人身份验证凭证(如密码)、私信聊天内容等。 以上各个行业的共同特点是都涉及到大量高度机密性的客户私人信息存储与传输活动,因此实施有效的数据脱敏措施显得尤为重要[^4]。 #### 实现方及示例 以下是几种常见的实现方式及其对应的Python代码片段: ##### 字符串遮蔽 适用于短文本字段,比如名字首字母加随机数填充其余位的方式。 ```python def mask_string(s, show_chars=2): """Mask string by showing only first few characters.""" masked_part = '*' * (len(s) - show_chars) return s[:show_chars] + masked_part if len(s)>show_chars else s ``` ##### 加密解密机制 利用强大的AES对称加密库PyCryptodome来进行双向安全编码。 ```python from Crypto.Cipher import AES import base64 class AesEncryption: def __init__(self,key='your-secret-key'): self.key=key.encode('utf8') def encrypt(self,message): cipher=AES.new(self.key,AES.MODE_EAX) nonce=cipher.nonce ciphertext,tag =cipher.encrypt_and_digest(message.encode()) encrypted_message={'ciphertext':base64.b64encode(ciphertext).decode(), 'nonce':base64.b64encode(nonce).decode()} return encrypted_message def decrypt(self,encripted_data): try: decipher=AES.new(self.key,AES.MODE_EAX, nonce=base64.b64decode(encripted_data['nonce'])) decrypted_text=decipher.decrypt(base64.b64decode( encripted_data['ciphertext'])).decode() return decrypted_text except Exception as e: print(f"Decryption failed: {e}") return None ``` ##### Hash散列函数 不可逆单向哈希运算适合长期保存但不需要还原的情况,像用户登录名之的唯一标识符。 ```python import hashlib def hash_password(password,salt=''): sha_signature =hashlib.sha256((password+salt).encode()).hexdigest() return sha_signature ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值