序文
RSAを使用すると、公開鍵のサイズを選択できます。512ビットキーは安全でないと見なされます。768ビットキーは国家安全保障局(NSA)以外の何かによって危険にさらされることを心配する必要はありません。1024ビットキーはほぼ安全です。RSAは、Windows、Netscape Navigator、Quicken、LotusNotesなどの主要な製品に組み込まれています。
RSA公開鍵暗号システムの原理は次のとおりです。数論によれば、2つの大きな素数を見つけるのは比較的簡単ですが、それらの積を因数分解することは非常に難しいため、積を暗号鍵として公に使用できます。
(1)2つの異なる大きな素数pとqを任意に選択して、積を計算します。
(2)を満たすために任意に大きな整数eを選択します
整数eが暗号化キーとして使用されます(注:eの選択は簡単です。たとえば、pおよびqより大きいすべての素数を使用できます)。
(3)決定された復号化キーdは
これは
は任意の整数です。したがって、eと
、dの計算は簡単です。
(4)整数nとeが開示され、dは秘密にされます。
(5)平文m(m <nは整数)を暗号文cに暗号化し、暗号化アルゴリズムは次のようになります。
(6)暗号文cを平文mに復号化します。復号化アルゴリズムは次のとおりです。
ただし、nとeだけでdを計算することはできません(注:pとqではありません)。したがって、誰でも平文を暗号化できますが、暗号文を復号化できるのは許可されたユーザー(dを知っている)だけです。
1.オンライン暗号化と復号化
https://www.bejson.com/enc/rsa/
https://www.bejson.com/enc/sha/
2.RSA暗号化
RSA暗号化にはキーが必要であり、特定のキー文字列を自分で定義する必要があります
public static String getRSAPublidKeyBybase64(String KEY, String text) {
Cipher cipher;
try {
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");//Android上使用
byte[] publicBytes = Base64.decode(KEY.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] encryptedBytes = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
} catch (NoSuchAlgorithmException | NoSuchPaddingException |
InvalidKeyException | BadPaddingException | IllegalBlockSizeException |
InvalidKeySpecException e) {
e.printStackTrace();
}
return "";
}
3.SHA暗号化
SHA暗号化タイプ
暗号化タイプを入力する場合:SHA-512
/**
* SHA加密
* @param strText 待加密的字符串
* @param strType 加密类型
* @return 加密后的字符串
*/
public static String SHA(final String strText, final String strType) {
// 返回值
String strResult = null;
// 是否是有效字符串
if (strText != null && strText.length() > 0) {
try {
// SHA 加密开始
// 创建加密对象 并傳入加密類型
MessageDigest messageDigest = MessageDigest.getInstance(strType);
// 传入要加密的字符串
messageDigest.update(strText.getBytes());
// 得到 byte 類型结果
byte[] byteBuffer = messageDigest.digest();
// 將 byte 轉換爲 string
StringBuilder strHexString = new StringBuilder();
// 遍歷 byte buffer
for (byte b : byteBuffer) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
strHexString.append('0');
}
strHexString.append(hex);
}
// 得到返回結果
strResult = strHexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
return strResult;
}