cryptage asymétrique
L'algorithme de chiffrement asymétrique est également appelé algorithme de chiffrement moderne. Le cryptage asymétrique est la pierre angulaire de la sécurité des communications informatiques, garantissant que les données cryptées ne seront pas piratées.
Contrairement aux algorithmes de chiffrement symétriques, les algorithmes de chiffrement asymétriques nécessitent deux clés : la clé publique (publickey) et la clé privée (privatekey)
Une clé publique et une clé privée forment une paire. Si les données sont chiffrées avec une clé publique, elles ne peuvent être déchiffrées qu'avec la clé privée correspondante. Si les données sont chiffrées avec une clé privée, elles ne peuvent être déchiffrées qu'avec la clé publique correspondante.
Étant donné que le chiffrement et le déchiffrement utilisent deux clés différentes, cet algorithme est appelé algorithme de chiffrement asymétrique.
caractéristiques
Le chiffrement et le déchiffrement utilisent des clés différentes
S'il est chiffré avec la clé privée, il ne peut être déchiffré qu'avec la clé publique
S'il est chiffré avec la clé publique, il ne peut être déchiffré qu'avec la clé privée
Le traitement des données est plus lent en raison du niveau de sécurité élevé
exemple
Générez d'abord une paire de clés, la clé publique est (5,14), la clé privée est (11,14), A veut envoyer le texte original 2 à B
A utilise la clé publique pour chiffrer les données. 2 à la puissance 5 mod 14 = 4 , envoyer le texte chiffré 4 à B
B utilise la clé privée pour déchiffrer les données. 4 à la puissance 11 mod14 = 2, obtenir le texte original 2
1 Algorithmes communs
RSA
RSA a été proposé en 1977 par Ronald Rivest (Ron Rivest), Adi Shamir (Adi Shamir) et Leonard Adleman (Leonard Adleman).
Le cryptosystème à clé publique RSA est une sorte d'utilisation de clé de cryptage et de clé de décryptage différentes.
RSA peut résister à la grande majorité des attaques cryptographiques connues jusqu'à présent et a été recommandé par l'ISO comme norme de chiffrement des données à clé publique. Seules les clés RSA courtes peuvent être piratées par la force brute. Il n'existe pas encore de moyen fiable d'attaquer l'algorithme RSA dans le monde. Tant que la longueur de la clé est suffisamment longue, les informations chiffrées avec RSA ne peuvent pas être piratées.
L'algorithme RSA est basé sur un fait très simple de la théorie des nombres : il est très facile de multiplier deux grands nombres premiers, mais il est extrêmement difficile de factoriser le produit, de sorte que le produit peut être rendu public en tant que clé de chiffrement.
Outils en ligne RSA
Amis qui veulent en savoir plus sur RSA, veuillez passer à l'algorithme RSA de chiffrement à clé publique
ECC (cryptographie à courbe elliptique)
2 Générer des clés publiques et privées
public static void main ( String [ ] args) throws NoSuchAlgorithmException {
String algorithm = "RSA" ;
KeyPairGenerator keyPairGenerator = KeyPairGenerator . getInstance ( algorithm) ;
KeyPair keyPair = keyPairGenerator. generateKeyPair ( ) ;
PrivateKey privateKey = keyPair. getPrivate ( ) ;
PublicKey publicKey = keyPair. getPublic ( ) ;
byte [ ] privateKeyEncoded = privateKey. getEncoded ( ) ;
byte [ ] publicKeyEncoded = publicKey. getEncoded ( ) ;
String privateKeyString = Base64 . encodeBase64String ( privateKeyEncoded) ;
String publicKeyString = Base64 . encodeBase64String ( publicKeyEncoded) ;
System . out. println ( "私钥:" + privateKeyString) ;
System . out. println ( "共钥:" + publicKeyString) ;
}
私钥:MIIG/QIBADANBgkqhkiG9w0BAQEFAASCBucwggbjAgEAAoIBgQC6hpkMQs+D0XefTNESooz3Cauz8Tpl7NaHKm3X8ZrqLO/QfCqW2ZoozlkXFi7nzNwPQ
BfEv1VgXhiT5VOy+r24Lcc3oakNtSWXYuBoXraJXdpE7EqVKdPSZbxzT3OhSQ0QqX3F2Y19euz5RB8jD9GBEJ+VHTnBKIpugX4irCWj1TYKbB8XGbH85wcWG
4uH2kn41DqM8IPw9TTDpMoyW7BEHShulOS+7G1Nd7rrtaf0tCyk9bVdms9Ou+JzKWRfCQFxuEH1sWvijW4R83OQYfpGa2kvJgiUQP0O9TQCmp0+ImWiThWfY
biqrFyJVynIDko8mFXXWolmdfq1myuNg126sUe1wPmZhtIC595hp965K8bwTiSg8weuSXOkAXJ7Cr4OLCOimSrB4qdLueqjAhMcQWuHXbGZCqnrbtOFmzxxR
NH8TWjhyPvtXldf7bK0CQaSuE2kfAi7YKwBwzI8iAbVomYh7EdVvMHq/YlwEPg8DqcuAJODaqcnZsy7om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XwkBcbhB9bFr4o1uEfNzkGH6RmtpLyYIlED9DvU0ApqdPiJlok4Vn2G4qqxci
VcpyA5KPJhV11qJZnX6tZsrjYNdurFHtcD5mYbSAufeYafeuSvG8E4koPMHrklzpAFyewq+DiwjopkqweKnS7nqowITHEFrh12xmQqp627ThZs8cUTR/E1o4
cj77V5XX+2ytAkGkrhNpHwIu2CsAcMyPIgG1aJmIexHVbzB6v2JcBD4PA6nLgCTg2qnJ2bMu6JirmVnAgMBAAE=
3 cryptage par clé privée
public static void main( String[ ] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
String input = "国泰民安" ;
// 加密算法
String algorithm = "RSA" ;
// 创建密钥对生成器对象
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance( algorithm) ;
// 生成密钥对
KeyPair keyPair = keyPairGenerator.generateKeyPair( ) ;
// 生成私钥
PrivateKey privateKey = keyPair.getPrivate( ) ;
// 生成公钥
PublicKey publicKey = keyPair.getPublic( ) ;
// 创建加密对象
// 参数表示加密算法
Cipher cipher = Cipher.getInstance( algorithm) ;
// 初始化加密
// 第一个参数:加密的模式
// 第二个参数:使用私钥进行加密
cipher.init( Cipher.ENCRYPT_MODE,privateKey) ;
// 私钥加密
byte[ ] bytes = cipher.doFinal( input.getBytes( )) ;
System.out.println( Base64.encodeBase64String( bytes)) ;
}
gjfiD1F+DOFk2IHqrTWSKe+8qGLCihNuu+RrZY6CKji0H56RUhSL3P5fW2X3FXpCrY+CMsGg16HfmR3boeX1qY4e0NJU0JtE1Ch4uERigH1eM/MUCUaFaVI4
9roDAcqbz0v+lnsX41mOCQ4YSd742XoIg7cJX1GcsHhkXDF3JCM/fDxdHYR63ApmSpzr+qfoelntnc+Xah90i3UR/PPiEZ6/6JWz7mU5DK/X5IVnqgGObNCl
syH7tWcwl34IcrszFvK4ovtxeYVQken7IHgW8LMCxWGXWyDThC+9A/d9AV9vlLLuzZcYEvRYMS5BzZqr9gzdrgYE1hsRouFQ0yyuOUoVAbaqAjqhPRTTIj0E
QUl2PpB7hi561x/j/58w9dsoI3gKp/G6SBl40yyuxbm5z/RGYxjeZhyIC4Lm/ddpCQpJ5qzZ/WX6N9fSqjwQLaHSQpgmsy5zdZRkZchxknw8LgONSzObwA5/
F561oXgtHWD44+SzZHoOGY3hDSU3oKMT
4 chiffrement à clé privée déchiffrement à clé publique
Cryptage à clé privée, uniquement décryptage à clé publique
public static void main ( String [ ] args) throws NoSuchAlgorithmException , InvalidKeyException , NoSuchPaddingException , IllegalBlockSizeException , BadPaddingException {
String input = "国泰民安" ;
System . out. println ( input) ;
String algorithm = "RSA" ;
KeyPairGenerator keyPairGenerator = KeyPairGenerator . getInstance ( algorithm) ;
KeyPair keyPair = keyPairGenerator. generateKeyPair ( ) ;
PrivateKey privateKey = keyPair. getPrivate ( ) ;
PublicKey publicKey = keyPair. getPublic ( ) ;
Cipher cipher = Cipher . getInstance ( algorithm) ;
cipher. init ( Cipher . ENCRYPT_MODE, privateKey) ;
byte [ ] bytes = cipher. doFinal ( input. getBytes ( ) ) ;
System . out. println ( Base64 . encodeBase64String ( bytes) ) ;
cipher. init ( Cipher . DECRYPT_MODE, publicKey) ;
byte [ ] bytes1 = cipher. doFinal ( bytes) ;
System . out. println ( new String ( bytes1) ) ;
}
国泰民安
VfUXV9TiXxeRx5/gq13GtsNm76BSw/63e1SaOI1szLnb9DjE4hfCmim0qqqOQYSp5fyE45694Dlj37p7/+eu7gMAuJN5PYZfN7bYQZ+ZIJeXCiEO/IWXFzQW
yIgoyqUjZ1i6ja0yfHhY0FXkBBJCr2SNwBiMW1lEQav0UE/i05Dj3+OOKDTKNbIgMLcsZfM3WPSNJWJq7bthnjO0KTPSdG5Dl+/eJictaSGTk0it5+D1l4G6
N8CfTfshG9c3vWbfmqgmU8GaA5Iqo1eHINPpS9SZOoAAokGEzmDkx2VJQiQO3GELIdcCGvyWvZIm7PlAV8EYzxTQiHRSuwiCJyGGABC+I9iEFwDaZwYCTAh7
roSwtpt1ax/KgQfbhv8vNE+/3ADnnvFgzDX6LfWuSl0vhclh9kl0ECnIICJd6dxKwCAZkctiwdOoPrbGnK4lWXbeTbdkxBpdw9LcnWMkCuCVy53k47OjB3S+
t+Uktr2snJAjJDYG4ZZmrQpEIj17zLKZ
国泰民安
5 Enregistrer et lire la clé publique et la clé privée
5.1 Enregistrer la clé publique et la clé privée
public static void main ( String [ ] args) throws Exception {
String input = "硅谷" ;
String algorithm = "RSA" ;
generateKeyToFile ( algorithm, "a.pub" , "a.pri" ) ;
}
private static void generateKeyToFile ( String algorithm, String pubPath, String priPath) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator . getInstance ( algorithm) ;
KeyPair keyPair = keyPairGenerator. generateKeyPair ( ) ;
PublicKey publicKey = keyPair. getPublic ( ) ;
PrivateKey privateKey = keyPair. getPrivate ( ) ;
byte [ ] publicKeyEncoded = publicKey. getEncoded ( ) ;
byte [ ] privateKeyEncoded = privateKey. getEncoded ( ) ;
String publicKeyString = Base64 . encodeBase64String ( publicKeyEncoded) ;
String privateKeyString = Base64 . encodeBase64String ( privateKeyEncoded) ;
FileUtils . writeStringToFile ( new File ( pubPath) , publicKeyString, Charset . forName ( "UTF-8" ) ) ;
FileUtils . writeStringToFile ( new File ( priPath) , privateKeyString, Charset . forName ( "UTF-8" ) ) ;
}
5.2 Lire les clés publiques et privées
public static void main ( String [ ] args) throws Exception {
String input = "明德新民,止于至善" ;
String algorithm = "RSA" ;
generateKeyToFile ( algorithm, "a.pub" , "a.pri" ) ;
PrivateKey privateKey = getPrivateKey ( "a.pri" , algorithm) ;
PublicKey publicKey = getPublicKey ( "a.pub" , algorithm) ;
String s = encryptRSA ( algorithm, privateKey, input) ;
String res = decryptRSA ( algorithm, publicKey, s) ;
System . out. println ( res) ;
}
public static String decryptRSA ( String algorithm, Key key, String encrypted) throws Exception {
Cipher cipher = Cipher . getInstance ( algorithm) ;
cipher. init ( Cipher . DECRYPT_MODE, key) ;
byte [ ] decode = Base64 . decodeBase64 ( encrypted) ;
byte [ ] bytes1 = cipher. doFinal ( decode) ;
return new String ( bytes1) ;
}
public static String encryptRSA ( String algorithm, Key key, String input) throws Exception {
Cipher cipher = Cipher . getInstance ( algorithm) ;
cipher. init ( Cipher . ENCRYPT_MODE, key) ;
byte [ ] bytes = cipher. doFinal ( input. getBytes ( ) ) ;
return Base64 . encodeBase64String ( bytes) ;
}
public static PublicKey getPublicKey ( String pulickPath, String algorithm) throws Exception {
String publicKeyString = FileUtils . readFileToString ( new File ( pulickPath) , Charset . defaultCharset ( ) ) ;
KeyFactory keyFactory = KeyFactory . getInstance ( algorithm) ;
X509EncodedKeySpec spec = new X509EncodedKeySpec ( Base64 . decodeBase64 ( publicKeyString) ) ;
return keyFactory. generatePublic ( spec) ;
}
private static void generateKeyToFile ( String algorithm, String pubPath, String priPath) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator . getInstance ( algorithm) ;
KeyPair keyPair = keyPairGenerator. generateKeyPair ( ) ;
PublicKey publicKey = keyPair. getPublic ( ) ;
PrivateKey privateKey = keyPair. getPrivate ( ) ;
byte [ ] publicKeyEncoded = publicKey. getEncoded ( ) ;
byte [ ] privateKeyEncoded = privateKey. getEncoded ( ) ;
String publicKeyString = Base64 . encodeBase64String ( publicKeyEncoded) ;
String privateKeyString = Base64 . encodeBase64String ( privateKeyEncoded) ;
FileUtils . writeStringToFile ( new File ( pubPath) , publicKeyString, Charset . forName ( "UTF-8" ) ) ;
FileUtils . writeStringToFile ( new File ( priPath) , privateKeyString, Charset . forName ( "UTF-8" ) ) ;
}
public static PrivateKey getPrivateKey ( String priPath, String algorithm) throws Exception {
String privateKeyString = FileUtils . readFileToString ( new File ( priPath) , Charset . defaultCharset ( ) ) ;
KeyFactory keyFactory = KeyFactory . getInstance ( algorithm) ;
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec ( Base64 . decodeBase64 ( privateKeyString) ) ;
return keyFactory. generatePrivate ( spec) ;
}