Asymmetric encryption algorithm-RSA signature & Verification Authorization

Source: Internet
Author: User
Tags base64 sort urlencode asymmetric encryption


Jie 2017/12/27



Applicable background: The host platform does not provide an OAuth 2.0 authorization method









The host platform RSA generates the secret key (secret key format: PKCS8) and provides the public key to your platform.



1) when the user (logged in) requests your platform service provided by the hosting platform, the host platform platform generates a signature for the user information with the private key



2) host platform jump to specify your platform URL, parameters include user information and sign = signature



3) your platform verification:



If the verification is successful, your platform platform based on the host platform user mobile phone number as the host platform of the user's unique identity to the silent login or registration;



Otherwise, prompt for a verification failure.

  1. The host platform creates a signature with the private key for user information






1) The content to be signed is the specified user information, including



orderid=10086



amount=399.00



creditamount=10000.0



mobile=18888888888



2) sort the parameters into a dictionary, form a string, and get the string to be signed



amount=399.00&creditamount=10000.0&mobile=18888888888&orderid=10086



3) Signature mode Sha1withrsa, generate signature s



q2rtzzkmqudcvavsd7yvf5auvnajerllagmn1cif1ctufsj9pms7x9rfbcsle5ifetgweyosbquv2lpupxabjed1dlzqidxcfoypprlwmotqmlvcxzxhykw5b 958aiunjm6_f_zkiefuu7lgpmjpgoxi90qxjypqbpaxcby3oas=



4) Assign the generated signature s to the sign parameter, put the signs in the request parameters, and then urlencode each parameter value url?amount=399.00&creditamount=10000.0&mobile= 18888888888&orderid=10086&sign= q2rtzzkmqudcvavsd7yvf5auvnajerllagmn1cif1ctufsj9pms7x9rfbcsle5ifetgweyosbquv2lpupxabjed1dlzqidxcfoypprlwmotqmlvcxzxhykw5b 958aiunjm6_f_zkiefuu7lgpmjpgoxi90qxjypqbpaxcby3oas%3d






2. Your platform is checked with a public key



1) Remove the parameters for verification



2) The parameters are UrlEncode, and the dictionary is sorted, the string is composed, and the string to be signed



3) Use Base64 to decode the value of the sign parameter to a bytecode string using RSA's verification method, signed by the string to be signed, the value of the sign parameter, and the public key



3. Appendix: RSA Sample Code





import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
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 java.util.TreeMap;

import org.springframework.util.Base64Utils;

/ **
 * Asymmetric encryption algorithm-RSA
 *
 * @author jie
 *
 * /
public class RSA {
/ ** RSA algorithm * /
private static final String RSA_ALGORITHM = "RSA";
/ ** RSA signature algorithm * /
private static final String RSA_SIGNATURE_ALGORITHM = "SHA1withRSA";
/ ** RSA public key key * /
public static final String RSA_PUBLIC_KEY = "RSA_PUBLIC_KEY";
/ ** RSA private key * /
public static final String RSA_PRIVATE_KEY = "RSA_PRIVATE_KEY";

/ **
* Generate RSA public and private key pair: key format PKCS8
*
* @param keysize
* Key length: 1024, 2048
* @return RSA public and private key pair Map <String, String>
* @throws Exception
* /
public static Map <String, String> generateKeyPair (Integer keysize) throws Exception {
// Generate RSA Key
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance (RSA_ALGORITHM);
keyPairGenerator.initialize (keysize);
KeyPair keyPair = keyPairGenerator.generateKeyPair ();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic ();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate ();
// Key-> Base64
String publicKeyBase64 = Base64Utils.encodeToUrlSafeString (publicKey.getEncoded ());
String privateKeyBase64 = Base64Utils.encodeToUrlSafeString (privateKey.getEncoded ());

Map <String, String> ret = new HashMap <String, String> ();
ret.put (RSA_PUBLIC_KEY, publicKeyBase64);
ret.put (RSA_PRIVATE_KEY, privateKeyBase64);
return ret;
}

/ **
* RSA private key signature: SHA1withRSA
*
* @param data
* To be signed byte []
* @param privateKeyBase64
* Private key (Base64 encoded)
* @return signature byte []
* @throws Exception
* /
public static byte [] sign (byte [] data, String privateKeyBase64) throws Exception {
// Base64-> Key
byte [] bytes = Base64Utils.decodeFromUrlSafeString (privateKeyBase64);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec (bytes);
KeyFactory keyFactory = KeyFactory.getInstance (RSA_ALGORITHM);
PrivateKey privateKey = keyFactory.generatePrivate (keySpec);
// Sign
Signature signature = Signature.getInstance (RSA_SIGNATURE_ALGORITHM);
signature.initSign (privateKey);
signature.update (data);
return signature.sign ();
}

/ **
* RSA public key verification
*
* @param data
* String to be signed
* @param publicKeyBase64
* Public key (Base64 encoded)
* @return verification result
* @throws Exception
* /
public static boolean verify (byte [] data, String publicKeyBase64, String sign) throws Exception {
// Base64-> Key
byte [] bytes = Base64Utils.decodeFromUrlSafeString (publicKeyBase64);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec (bytes);
KeyFactory keyFactory = KeyFactory.getInstance (RSA_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic (keySpec);
// verify
Signature signature = Signature.getInstance (RSA_SIGNATURE_ALGORITHM);
signature.initVerify (publicKey);
signature.update (data);
return signature.verify (Base64Utils.decodeFromUrlSafeString (sign));
}

public static void main (String [] args) {
try {
// 0. Generate public and private key pairs
Map <String, String> keyPair = RSA.generateKeyPair (1024);
System.out.println ("Private Key:" + keyPair.get (RSA_PRIVATE_KEY));
System.out.println ("Public Key:" + keyPair.get (RSA_PUBLIC_KEY));

// Sort parameters by dictionary
StringBuilder sb = new StringBuilder ();
Map <String, String> map = new TreeMap <String, String> ();
map.put ("orderId", "10086");
map.put ("mobile", "18888888888");
// make up the string to be signed
sb.delete (0, sb.length ()); // clear StringBuilder
for (Map.Entry <String, String> entry: map.entrySet ()) {
if (sb.toString (). contains ("="))
sb.append ("&");
sb.append (entry.getKey () + "=" + entry.getValue ());
}
String signContent = sb.toString ();
System.out.println ("Content to be signed:" + signContent);

// 1. Generate signature with private key
byte [] signBytes = RSA.sign (signContent.getBytes (), keyPair.get (RSA_PRIVATE_KEY));
String sign = Base64Utils.encodeToUrlSafeString (signBytes);
System.out.println ("Signature:" + sign);

// 2. Sign check with public key
boolean verify = RSA.verify (signContent.getBytes (), keyPair.get (RSA_PUBLIC_KEY), sign);
System.out.println ("Check result:" + verify);
} catch (Exception e) {
e.printStackTrace ();
}
}
} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.