-
RSA加密
2019-10-28 20:43:38RSA 加密时,对要加密数据的大小有限制,最大不大于密钥长度。例如在使用 1024 bit 的密钥时(genrsa -out rsa_private_key.pem 1024),最大可以加密 1024/8=128 Bytes 的数据。数据大于 128 Bytes 时,...生成公钥私钥配对加解密
注意:
RSA 加密或签名后的结果是不可读的二进制,使用时经常会转为 BASE64 码再传输。
RSA 加密时,对要加密数据的大小有限制,最大不大于密钥长度。例如在使用 1024 bit 的密钥时(genrsa -out rsa_private_key.pem 1024),最大可以加密 1024/8=128 Bytes 的数据。数据大于 128 Bytes 时,需要对数据进行分组加密(如果数据超限,加解密时会失败,openssl 函数会返回 false),分组加密后的加密串拼接成一个字符串后发送给客户端。
为了保证每次加密的结果都不同,RSA 加密时会在待加密数据后拼接一个随机字符串,再进行加密。不同的填充方式 Padding 表示这个字符串的不同长度,在对超限数据进行分组后,会按照这个 Padding 指定的长度填入随机字符串。例如如果 Padding 填充方式使用默认的 OPENSSL_PKCS1_PADDING(需要占用 11 个字节用于填充),那么明文长度最多只能就是 128-11=117 Bytes。
一般默认使用 OPENSSL_PKCS1_PADDING。PHP 支持的 Padding 有 OPENSSL_PKCS1_PADDING、OPENSSL_SSLV23_PADDING、OPENSSL_PKCS1_OAEP_PADDING 和 OPENSSL_NO_PADDING。
接收方解密时也需要分组。将加密后的原始二进制数据(对于经过 BASE64 的数据,需要解码),每 128 Bytes 分为一组,然后再进行解密。解密后,根据 Padding 的长度丢弃随机字符串,把得到的原字符串拼接起来,就得到原始报文。
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.util.Base64Utils;
import com.bessky.hrmis.common.uconfig.UConfigHelper;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
public class RSAHelper
{
private static final String publicKeyBase64 = "";
private static final String privateKeyBase64 = "";
/**
* RSA密钥长度必须是64的倍数,在512~65536之间。默认是1024
*/
public static final int KEY_SIZE = 2048;
/**
* 获取公钥对象
*
* @param publicKeyBase64
* @return
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
*/
public static PublicKey getPublicKey(String publicKeyBase64) throws InvalidKeySpecException, NoSuchAlgorithmException, Base64DecodingException
{
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec publicpkcs8KeySpec = new X509EncodedKeySpec(Base64.decode(publicKeyBase64));
PublicKey publicKey = keyFactory.generatePublic(publicpkcs8KeySpec);
return publicKey;
}
/**
* 获取私钥对象
*
* @param privateKeyBase64
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey getPrivateKey(String privateKeyBase64) throws NoSuchAlgorithmException, InvalidKeySpecException, Base64DecodingException
{
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec privatekcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decode(privateKeyBase64));
PrivateKey privateKey = keyFactory.generatePrivate(privatekcs8KeySpec);
return privateKey;
}
/**
* 使用工钥加密
*
* @param content 待加密内容
* @param publicKeyBase64 公钥 base64 编码
* @return 经过 base64 编码后的字符串
*/
public static String encipher(String content)
{
return encipher(content, publicKeyBase64, KEY_SIZE / 8 - 11);
}
/**
* 使用公司钥加密(分段加密)
*
* @param content 待加密内容
* @param publicKeyBase64 公钥 base64 编码
* @param segmentSize 分段大小,一般小于 keySize/8(段小于等于0时,将不使用分段加密)
* @return 经过 base64 编码后的字符串
*/
public static String encipher(String content, String publicKeyBase64, int segmentSize)
{
try
{
PublicKey publicKey = getPublicKey(publicKeyBase64);
return encipher(content, publicKey, segmentSize);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
/**
* 分段加密
*
* @param ciphertext 密文
* @param key 加密秘钥
* @param segmentSize 分段大小,<=0 不分段
* @return
*/
public static String encipher(String ciphertext, java.security.Key key, int segmentSize)
{
try
{
// 用公钥加密
byte[] srcBytes = ciphertext.getBytes();
// Cipher负责完成加密或解密工作,基于RSA
Cipher cipher = Cipher.getInstance("RSA");
// 根据公钥,对Cipher对象进行初始化
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] resultBytes = null;
if (segmentSize > 0)
resultBytes = cipherDoFinal(cipher, srcBytes, segmentSize); // 分段加密
else
resultBytes = cipher.doFinal(srcBytes);
String base64Str = Base64Utils.encodeToString(resultBytes);
return base64Str;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
/**
* 分段大小
*
* @param cipher
* @param srcBytes
* @param segmentSize
* @return
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws IOException
*/
public static byte[] cipherDoFinal(Cipher cipher, byte[] srcBytes, int segmentSize) throws IllegalBlockSizeException, BadPaddingException, IOException
{
if (segmentSize <= 0)
throw new RuntimeException("分段大小必须大于0");
ByteArrayOutputStream out = new ByteArrayOutputStream();
int inputLen = srcBytes.length;
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0)
{
if (inputLen - offSet > segmentSize)
{
cache = cipher.doFinal(srcBytes, offSet, segmentSize);
}
else
{
cache = cipher.doFinal(srcBytes, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * segmentSize;
}
byte[] data = out.toByteArray();
out.close();
return data;
}
/**
* 使用私钥解密
*
* @param contentBase64 待加密内容,base64 编码
* @param privateKeyBase64 私钥 base64 编码
* @return
* @segmentSize 分段大小
*/
public static String decipher(String contentBase64)
{
return decipher(contentBase64, privateKeyBase64, KEY_SIZE / 8);
}
/**
* 使用私钥解密(分段解密)
*
* @param contentBase64 待加密内容,base64 编码
* @param privateKeyBase64 私钥 base64 编码
* @return
* @segmentSize 分段大小
*/
public static String decipher(String contentBase64, String privateKeyBase64, int segmentSize)
{
try
{
PrivateKey privateKey = getPrivateKey(privateKeyBase64);
return decipher(contentBase64, privateKey, segmentSize);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
/**
* 分段解密
*
* @param contentBase64 密文
* @param key 解密秘钥
* @param segmentSize 分段大小(小于等于0不分段)
* @return
*/
public static String decipher(String contentBase64, java.security.Key key, int segmentSize)
{
try
{
// 用私钥解密
byte[] srcBytes = Base64Utils.decodeFromString(contentBase64);
// Cipher负责完成加密或解密工作,基于RSA
Cipher deCipher = Cipher.getInstance("RSA");
// 根据公钥,对Cipher对象进行初始化
deCipher.init(Cipher.DECRYPT_MODE, key);
byte[] decBytes = null;// deCipher.doFinal(srcBytes);
if (segmentSize > 0)
decBytes = cipherDoFinal(deCipher, srcBytes, segmentSize); // 分段加密
else
decBytes = deCipher.doFinal(srcBytes);
String decrytStr = new String(decBytes);
return decrytStr;
}
catch (Exception e)
{
e.printStackTrace();
}
}
} -
RSA 加密
2013-08-29 22:35:35用RSA加密的数据只能用私钥解密,而用私钥签名的数据只能用公钥验证。公钥可以提供给任何人;公钥用于对要发送到私钥持有者的数据进行加密。两个密钥对于通信会话都是唯一的。RSA 加密算法也称为不对称算法,原因是...RSA 加密使用一个必须对未经授权的用户保密的私钥和一个可以对任何人公开的公钥。公钥和私钥都在数学上相关联;用RSA加密的数据只能用私钥解密,而用私钥签名的数据只能用公钥验证。公钥可以提供给任何人;公钥用于对要发送到私钥持有者的数据进行加密。两个密钥对于通信会话都是唯一的。RSA 加密算法也称为不对称算法,原因是需要用一个密钥加密数据而需要用另一个密钥来解密数据。
RSA 加密算法使用固定的缓冲区大小,而私钥加密算法使用长度可变的缓冲区。公钥算法无法像私钥算法那样将数据链接起来成为流,原因是它只可以加密少量数据。因此,不对称加密不使用与对称加密相同的流模型。
双方(小红和小明)可以按照下列方式使用 RSA 加密。首先,小红生成一个公钥/私钥对。如果小明想要给小红发送一条加密的消息,他将向她索要她的公钥。小红通过不安全的网络将她的公钥发送给小明,小明接着使用该密钥加密消息。(如果小明在不安全的信道如公共网络上收到小红的密钥,则小明必须同小红验证他具有她的公钥的正确副本。)小明将加密的消息发送给小红,而小红使用她的私钥解密该消息。
但是,在传输小红的公钥期间,未经授权的代理可能截获该密钥。而且,同一代理可能截获来自小明的加密消息。但是,该代理无法用公钥解密该消息。该消息只能用小红的私钥解密,而该私钥没有被传输。小红不使用她的私钥加密给小明的答复消息,原因是任何具有公钥的人都可以解密该消息。如果小红想要将消息发送回小明,她将向小明索要他的公钥并使用该 RSA 加密她的消息。然后,小明使用与他相关联的私钥来解密该消息。
在一个实际方案中,小红和小明使用公钥(不对称)加密来传输私(对称)钥,而对他们的会话的其余部分使用私钥加密。
RSA 加密具有更大的密钥空间(或密钥的可能值范围),因此不大容易受到对每个可能密钥都进行尝试的穷举攻击。由于不必保护公钥,因此它易于分发。公钥算法可用于创建数字签名以验证数据发送方的身份。但是,公钥算法非常慢(与私钥算法相比),不适合用来加密大量数据。公钥算法仅对传输很少量的数据有用。RSA 加密通常用于加密一个私钥算法将要使用的密钥。传输密钥,会话的其余部分将使用私钥加密。
RSA 加密也可以用来为一个消息署名(数字签名)。假如甲想给乙传递一个署名的消息的话,那么她可以为她的消息计算一个散列值(Message diget),然后用她的密钥(private key)加密这个散列值并将这个“署名”加在消息的后面。这个消息只有用她的公钥才能被解密。乙获得这个消息后可以用甲的公钥解密这个散列值,然后将这个数据与他自己为这个消息计算的散列值相比较。假如两者相符的话,那么他就可以知道发信人持有甲的密钥,以及这个消息在传播路径上没有被篡改过。
-
RSA加密与解密(Java实现)
2018-10-17 10:22:52现在,很多登陆表单的密码的都采用RSA加密,例如京东中的登陆使用公钥对密码进行加密。 Base64编码 apache.commons-codex包提供了许多编码格式转换,例如Base64。 以下为Base64编码表 使用apache.commons-...本文作者:合肥工业大学 管理学院 钱洋 email:1563178220@qq.com 内容可能有不到之处,欢迎交流。
未经本人允许禁止转载。
RSA的应用
RSA是一种非对称加密算法。现在,很多登陆表单的密码的都采用RSA加密,例如京东中的登陆使用公钥对密码进行加密。
Base64编码
apache.commons-codex包提供了许多编码格式转换,例如Base64。
以下为Base64编码表
使用apache.commons-codex进行Base64对字符串进行编码与解码的程序如下:package com.qian.encoded; import org.apache.commons.codec.binary.Base64; public class Base64Coded { public static void main(String[] args) { String string = "qianyang123"; //编码 String encode = encode(string.getBytes()); System.out.println(string + "\t编码后的字符串为:" + encode); //解码 String decode = decode(encode.getBytes()); System.out.println(encode + "\t字符串解码后为:" + decode); } //base64 解码 public static String decode(byte[] bytes) { return new String(Base64.decodeBase64(bytes)); } //base64 编码 public static String encode(byte[] bytes) { return new String(Base64.encodeBase64(bytes)); } }
程序的输出结果为:
qianyang123 编码后的字符串为:cWlhbnlhbmcxMjM=
cWlhbnlhbmcxMjM= 字符串解码后为:qianyang123RSA加密与解密
使用RSA一般需要产生公钥和私钥,当采用公钥加密时,使用私钥解密;采用私钥加密时,使用公钥解密。以下为Java程序:
package com.qian.encoded; import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; 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; public class RSAEncrypt { private static Map<Integer, String> keyMap = new HashMap<Integer, String>(); //用于封装随机产生的公钥与私钥 public static void main(String[] args) throws Exception { //生成公钥和私钥 genKeyPair(); //加密字符串 String message = "df723820"; System.out.println("随机生成的公钥为:" + keyMap.get(0)); System.out.println("随机生成的私钥为:" + keyMap.get(1)); String messageEn = encrypt(message,keyMap.get(0)); System.out.println(message + "\t加密后的字符串为:" + messageEn); String messageDe = decrypt(messageEn,keyMap.get(1)); System.out.println("还原后的字符串为:" + messageDe); } /** * 随机生成密钥对 * @throws NoSuchAlgorithmException */ public static void genKeyPair() throws NoSuchAlgorithmException { // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); // 初始化密钥对生成器,密钥大小为96-1024位 keyPairGen.initialize(1024,new SecureRandom()); // 生成一个密钥对,保存在keyPair中 KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥 String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded())); // 得到私钥字符串 String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded()))); // 将公钥和私钥保存到Map keyMap.put(0,publicKeyString); //0表示公钥 keyMap.put(1,privateKeyString); //1表示私钥 } /** * RSA公钥加密 * * @param str * 加密字符串 * @param publicKey * 公钥 * @return 密文 * @throws Exception * 加密过程中的异常信息 */ public static String encrypt( String str, String publicKey ) throws Exception{ //base64编码的公钥 byte[] decoded = Base64.decodeBase64(publicKey); RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded)); //RSA加密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8"))); return outStr; } /** * RSA私钥解密 * * @param str * 加密字符串 * @param privateKey * 私钥 * @return 铭文 * @throws Exception * 解密过程中的异常信息 */ public static String decrypt(String str, String privateKey) throws Exception{ //64位解码加密后的字符串 byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8")); //base64编码的私钥 byte[] decoded = Base64.decodeBase64(privateKey); RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); //RSA解密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, priKey); String outStr = new String(cipher.doFinal(inputByte)); return outStr; } }
在程序中,我们首先利用genKeyPair()函数生成公钥和私钥并将其保存到Map集合中。然后,基于产生的公钥对明文进行加密。针对已经已经加密的密文,我们再次使用私钥解密,得到明文。
上述程序的输出结果为:随机生成的公钥为:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCG77PYUAcCpANyUmsHJfuDIia9FcITsuu9lnfbE2BbEwd4SOxPBFTwEWTZ9/e+mtjP97KFEBohGkwy+VHE5KocypBv0O7YgEevwMgpvxyYY0v104CB/k0yjCFV7lc7FxY5VgEKrMiXTIkMr1ukCnWVvapvRCS6IFcsT/kkjPgfDQIDAQAB
随机生成的私钥为:MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIbvs9hQBwKkA3JSawcl+4MiJr0VwhOy672Wd9sTYFsTB3hI7E8EVPARZNn3976a2M/3soUQGiEaTDL5UcTkqhzKkG/Q7tiAR6/AyCm/HJhjS/XTgIH+TTKMIVXuVzsXFjlWAQqsyJdMiQyvW6QKdZW9qm9EJLogVyxP+SSM+B8NAgMBAAECgYEAhj0FH9dNghUE0MCpdS0WL/jTrRxuPQase6mrhyiZnUErF0EExf87OLE1MZr8voRx2UNEOBgyxmfREozyCfyqNg1OdGYEHSyuJ9wglkhq8GVYO8IzI29Mqej0MSprtsE0BPAKBHRU/DWP19ej5bv5ZnAhLs10K7uVEsuGwJJYcMECQQDibedUr7tnGfojyjFY0vCAaVwgS0vXfno7WQyAXUz0Fv8Uy1q9nyF0RrkeA8BOk7S4ljE77ufX0rr2qL7kHW8pAkEAmI718EnQCKKJUjrQUl4iG/lYoNwW2QnxTGZmESyFwkS95PTt8K4GVHpICqRNP1JJBNxVSEVts/eA4zrxPAoBRQJBAJxxEsOQJwq1B/5yVGXqWABgyyYE4AGjgRBAFkMaM3Dx8ouLdMZOi+6qbnwuW0/u/Y4LNzkRd13GWybQsBMrwwECQEULptmavpG55kaWIcS1n+BjSK59DcYrDs+SJK2vJdaXwA4IoEvmpyzCrypJ1EBNYIjXo61y5sSlxuqQua9/o7UCQGYdM3/mF/FEC3wxdfQq0Pw/Pwn8RQxg1natRfoTyzOJDfE/YUYGjIEe2pQtDI1s+IRCwrXOB0cySbpaSHCjr5U=
df723820 加密后的字符串为:HRMm2XsytNJjmnZgn+2pFZWyTn56tsp7/yII6jdo3Wb19uy8GFtFujMekcUWqwFsO9vbvUOyD21MgI85BOtD7tsHHlj5xdtPiFEHkY1qiWIHTPpxA+WICSlw9ZY4zY0IaoxhrMAb8c9ohsrbBbyGcmUSFFdZq8CuPfj99IDLLic=
还原后的字符串为:df723820 -
-
RSA加密法
2020-03-12 21:03:52RSA加密 RSA加密法也叫做公钥密码学加密法。 有两个密钥,一个用来加密,另一个用来解密。 使用一个密钥加密的消息只能使用另一个密钥解密。 公钥和全世界共享用于加密,密钥必须藏好用于解密。 RSA密钥创建 RSA体系...RSA加密
RSA加密法也叫做公钥密码学加密法。
有两个密钥,一个用来加密,另一个用来解密。
使用一个密钥加密的消息只能使用另一个密钥解密。
公钥和全世界共享用于加密,密钥必须藏好用于解密。RSA密钥创建
RSA体系的密钥由两个数字组成,创建密钥的步骤:
1.创建两个随机的非常大的质数,这些数字分布成为p和q。将这些数字相乘得到一个数字,称为n。2.创建一个随机数,称作e,使它与(p-1)*(q-1) 互质。
3.计算e的模逆,这个数字为d。
公钥是n和e两个数字,私钥是n和d两个数字。
其他用途
RSA加密法不仅提供加密,而且提供在文件或字符串上添加数字签名的方式。通过私钥来加密,世界上每个人都能通过公钥来解密
通过私钥加密就添加了数字签名,不能伪造。质询相应验证机制:
让他人的私钥加密自己给出的字符,自己用他人的公钥解密是否是自己的字符,如果是则证明他人身份。创建RSA密钥代码实现
import random, sys, os, rabinMiller, cryptomath def generateKey(keySize): # Creates a public/private key pair with keys that are keySize bits in # size. This function may take a while to run. # Step 1: Create two prime numbers, p and q. Calculate n = p * q. print('Generating p prime...') p = rabinMiller.generateLargePrime(keySize) print('Generating q prime...') q = rabinMiller.generateLargePrime(keySize) n = p * q # Step 2: Create a number e that is relatively prime to (p-1)*(q-1). print('Generating e that is relatively prime to (p-1)*(q-1)...') while True: # Keep trying random numbers for e until one is valid. e = random.randrange(2 ** (keySize - 1), 2 ** (keySize)) if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1: break # Step 3: Calculate d, the mod inverse of e. print('Calculating d that is mod inverse of e...') d = cryptomath.findModInverse(e, (p - 1) * (q - 1)) publicKey = (n, e) privateKey = (n, d) print('Public key:', publicKey) print('Private key:', privateKey) return (publicKey, privateKey) def makeKeyFiles(name, keySize): # Creates two files 'x_pubkey.txt' and 'x_privkey.txt' (where x is the # value in name) with the the n,e and d,e integers written in them, # delimited by a comma. # Our safety check will prevent us from overwriting our old key files: if os.path.exists('%s_pubkey.txt' % (name)) or os.path.exists('%s_privkey.txt' % (name)): sys.exit('WARNING: The file %s_pubkey.txt or %s_privkey.txt already exists! Use a different name or delete these files and re-run this program.' % (name, name)) publicKey, privateKey = generateKey(keySize) print() print('The public key is a %s and a %s digit number.' % (len(str(publicKey[0])), len(str(publicKey[1])))) print('Writing public key to file %s_pubkey.txt...' % (name)) fo = open('%s_pubkey.txt' % (name), 'w') fo.write('%s,%s,%s' % (keySize, publicKey[0], publicKey[1])) fo.close() print() print('The private key is a %s and a %s digit number.' % (len(str(publicKey[0])), len(str(publicKey[1])))) print('Writing private key to file %s_privkey.txt...' % (name)) fo = open('%s_privkey.txt' % (name), 'w') fo.write('%s,%s,%s' % (keySize, privateKey[0], privateKey[1])) fo.close() def main(): # create a public/private keypair with 1024 bit keys print('Making key files...') makeKeyFiles('al_sweigart', 1024) print('Key files made.') if __name__ == '__main__': main()
RSA加密解密实现
import sys # IMPORTANT: The block size MUST be less than or equal to the key size! # (Note: The block size is in bytes, the key size is in bits. There # are 8 bits in 1 byte.) DEFAULT_BLOCK_SIZE = 128 # 128 bytes BYTE_SIZE = 256 # One byte has 256 different values. def getBlocksFromText(message, blockSize=DEFAULT_BLOCK_SIZE): # Converts a string message to a list of block integers. Each integer # represents 128 (or whatever blockSize is set to) string characters. messageBytes = message.encode('ascii') # convert the string to bytes blockInts = [] for blockStart in range(0, len(messageBytes), blockSize): # Calculate the block integer for this block of text blockInt = 0 for i in range(blockStart, min(blockStart + blockSize, len(messageBytes))): blockInt += messageBytes[i] * (BYTE_SIZE ** (i % blockSize)) blockInts.append(blockInt) return blockInts def getTextFromBlocks(blockInts, messageLength, blockSize=DEFAULT_BLOCK_SIZE): # Converts a list of block integers to the original message string. # The original message length is needed to properly convert the last # block integer. message = [] for blockInt in blockInts: blockMessage = [] for i in range(blockSize - 1, -1, -1): if len(message) + i < messageLength: # Decode the message string for the 128 (or whatever # blockSize is set to) characters from this block integer. asciiNumber = blockInt // (BYTE_SIZE ** i) blockInt = blockInt % (BYTE_SIZE ** i) blockMessage.insert(0, chr(asciiNumber)) message.extend(blockMessage) return ''.join(message) def encryptMessage(message, key, blockSize=DEFAULT_BLOCK_SIZE): # Converts the message string into a list of block integers, and then # encrypts each block integer. Pass the PUBLIC key to encrypt. encryptedBlocks = [] n, e = key for block in getBlocksFromText(message, blockSize): # ciphertext = plaintext ^ e mod n encryptedBlocks.append(pow(block, e, n)) return encryptedBlocks def decryptMessage(encryptedBlocks, messageLength, key, blockSize=DEFAULT_BLOCK_SIZE): # Decrypts a list of encrypted block ints into the original message # string. The original message length is required to properly decrypt # the last block. Be sure to pass the PRIVATE key to decrypt. decryptedBlocks = [] n, d = key for block in encryptedBlocks: # plaintext = ciphertext ^ d mod n decryptedBlocks.append(pow(block, d, n)) return getTextFromBlocks(decryptedBlocks, messageLength, blockSize) def readKeyFile(keyFilename): # Given the filename of a file that contains a public or private key, # return the key as a (n,e) or (n,d) tuple value. fo = open(keyFilename) content = fo.read() fo.close() keySize, n, EorD = content.split(',') return (int(keySize), int(n), int(EorD)) def encryptAndWriteToFile(messageFilename, keyFilename, message, blockSize=DEFAULT_BLOCK_SIZE): # Using a key from a key file, encrypt the message and save it to a # file. Returns the encrypted message string. keySize, n, e = readKeyFile(keyFilename) # Check that key size is greater than block size. if keySize < blockSize * 8: # * 8 to convert bytes to bits sys.exit('ERROR: Block size is %s bits and key size is %s bits. The RSA cipher requires the block size to be equal to or greater than the key size. Either decrease the block size or use different keys.' % (blockSize * 8, keySize)) # Encrypt the message encryptedBlocks = encryptMessage(message, (n, e), blockSize) # Convert the large int values to one string value. for i in range(len(encryptedBlocks)): encryptedBlocks[i] = str(encryptedBlocks[i]) encryptedContent = ','.join(encryptedBlocks) # Write out the encrypted string to the output file. encryptedContent = '%s_%s_%s' % (len(message), blockSize, encryptedContent) fo = open(messageFilename, 'w') fo.write(encryptedContent) fo.close() # Also return the encrypted string. return encryptedContent def readFromFileAndDecrypt(messageFilename, keyFilename): # Using a key from a key file, read an encrypted message from a file # and then decrypt it. Returns the decrypted message string. keySize, n, d = readKeyFile(keyFilename) # Read in the message length and the encrypted message from the file. fo = open(messageFilename) content = fo.read() messageLength, blockSize, encryptedMessage = content.split('_') messageLength = int(messageLength) blockSize = int(blockSize) # Check that key size is greater than block size. if keySize < blockSize * 8: # * 8 to convert bytes to bits sys.exit('ERROR: Block size is %s bits and key size is %s bits. The RSA cipher requires the block size to be equal to or greater than the key size. Did you specify the correct key file and encrypted file?' % (blockSize * 8, keySize)) # Convert the encrypted message into large int values. encryptedBlocks = [] for block in encryptedMessage.split(','): encryptedBlocks.append(int(block)) # Decrypt the large int values. return decryptMessage(encryptedBlocks, messageLength, (n, d), blockSize) def main(): # Runs a test that encrypts a message to a file or decrypts a message # from a file. filename = 'encrypted_file.txt' # the file to write to/read from mode = 'encrypt' # set to 'encrypt' or 'decrypt' if mode == 'encrypt': message = '''"Journalists belong in the gutter because that is where the ruling classes throw their guilty secrets." -Gerald Priestland "The Founding Fathers gave the free press the protection it must have to bare the secrets of government and inform the people." -Hugo Black''' pubKeyFilename = 'al_sweigart_pubkey.txt' print('Encrypting and writing to %s...' % (filename)) encryptedText = encryptAndWriteToFile(filename, pubKeyFilename, message) print('Encrypted text:') print(encryptedText) elif mode == 'decrypt': privKeyFilename = 'al_sweigart_privkey.txt' print('Reading from %s and decrypting...' % (filename)) decryptedText = readFromFileAndDecrypt(filename, privKeyFilename) print('Decrypted text:') print(decryptedText) if __name__ == '__main__': main()
-
RSA加密与解密,python实现rsa加密
2019-04-23 11:56:56rsa是目前互联网主流加密方式,方式为私钥加密,公钥解密或...rsa加密相同内容每次的结果都是不一样的。 下面是python实现rsa加密的代码: import base64 import rsa pubkey = rsa.PublicKey.load_pkcs1_openssl_pem... -
vue-cli前端 RSA加密 django后台RSA加密
2019-04-17 16:25:36vue-cli:RSA加密 在vue-cli的项目文件目录下: npm install --save jsencrypt 在项目路径src下新建文件夹plugins(用于存放加解密方法.js文件) 在plugins下新建文件jssHttp.js import Vue from 'vue' import ... -
RSA加密的原理——为什么被公钥加密的可以被私钥解密?
2018-08-25 15:32:43RSA加密的原理——为什么被公钥加密的可以被私钥解密? 目录 一,RSA 数学理论基础 二,RSA实现原理 三,RSA加密的过程 四,参考文献 引言 在密码学最开始,都是使用的普通加密模式 A 用加密... -
Android RSA加密
2019-04-29 14:21:23Android RSA加密,通过模数和指数生成公钥,再通过公钥进行加密1.RSA加密简介2.废话不说,先上结果3.首先我们先通过模数和指数获取公钥2.然后我们通过生成的公钥来对字符串进行加密[通过RSA的模数和指数获取公钥然后... -
【RSA】——非对称加密及RSA加密算法
2019-07-24 11:27:07二、RSA加密算法 1、什么是RSA加密算法 2、RSA的加密原理 3、RSA加密的流程 4、实际开发中使用RSA加密需要注意的地方 一、非对称加密 1、什么是非对称加密? 非对称加密是指,需要用一对儿密钥,即... -
RSA加密算法原理
2019-10-08 00:58:01一、什么是RSA加密算法: 二、RSA加密过程: 三、RAS解密过程: 四、生成密钥对: 五、实践: 六、Java进行 RSA 加解密时不得不考虑到的那些事儿: 一、什么是RSA加密算法: RSA加密算法是一种非对称加密算法... -
RSA加密体制
2020-03-25 09:35:45RSA加密和解密都是求幂模运算 RSA加密体制数据来源 大的素数p、q确定N (p-1)*(q-1)确定e 计算e的模(p-1)*(q-1)逆得到d RSA加密的过程 RSA的公钥是(N,e),如果加密数字M,则密文C=M^e mod N RSA... -
delphi RSA加密
2013-07-23 15:10:38用delphi实现RSA加密、解密功能,包含源码 -
Android RSA加密解密demo
2014-08-23 14:37:48Android RSA加密解密demo,详情请参看博客:http://blog.csdn.net/bbld_/article/details/38777491 -
RSA加密解密
2018-08-02 10:00:54因为项目需要,最近做一个RSA加密解密的接口,使用Go进行开发,接口使用jsonrpc,go 对RSA加密解密有很好的支持,不过由于受限于底层单片机,所以上层应用需要做一些稍微的调整。 一、概要 RSA是一种非对称加密... -
在线RSA加密解密
2019-08-20 14:52:12RSA加密解密https://oktools.net/rsa -
springboot RSA加密解密
2020-04-07 19:08:51spring boot 使用RSA非对称加密,前后端传递参数加解密 java实现RSA 加密解密 -
iOS RSA加密(非对称加密)
2020-07-10 13:47:14返回上级目录:iOS面试和知识点整理 RSA应用场景 由于 RSA算法的加密解密速度要比对称算法速度慢很多,在实际应用中,通常采取如下: 1.数据本身的加密和解密使用对称...iOS之RSA加密解密与后台之间的双向加密详解 ... -
js使用RSA加密
2019-05-09 11:24:53为了防止Web页面的敏感信息泄露,我们需要使用RSA加密算法对数据进行加密。 JS中常用的RSA加密库有:jsencrypt,jsrsasign,js-crypto-rsa jsencrypt库的使用比较简单: 安装库 npm i jsencrypt 使用: import ... -
RSA加密算法源码
2016-02-23 09:31:15RSA加密算法源码 详情参见:http://blog.csdn.net/lemon_tree12138/article/details/50696926 -
js-RSA加密算法
2017-09-27 20:56:15可以用Java直接执行的RSA加密js,直接模拟前端js加密。java引擎直接执行! -
AES加密算法和RSA加密算法
2020-11-18 16:22:12RSA加密算法是一种非对称加密算法,什么是非对称加密?上面在线体验链接已经看到,RSA加密需要公钥,解密需要私钥,这公钥和私钥不一样,所以就是非对称加密 AES加密算法用到一个key值(随机生成一个字符串),这个... -
接口RSA加密
2019-05-21 23:21:14生活不易,一直在前进,一直在学习 工作中用到了RSA非对称加密,与java进行对接 对方实现的是分段加密,分段解密 python也可以实现分段加密,... rsa加密 :param biz_content: :param public_key: :return: ''' ... -
token加密——RSA加密
2020-04-27 15:03:50RSA加密工具类 RsaUtils.java package com.hahashujia.utils; import lombok.extern.slf4j.Slf4j; import org.apache.tomcat.util.codec.binary.Base64; import javax.crypto.Cipher; import java.security.... -
Python实现RSA加密算法
2018-10-26 20:51:35RSA加密算法 RSA Python实现RSA加密算法