Key Takeaways
RSA is a widely-used asymmetric encryption and signature algorithm known for its strong security based on the difficulty of factoring large integers.
It relies on the mathematical hardness of the integer factorization problem and has been a foundational cryptographic algorithm for decades.
Binance supports RSA for API security in certain contexts, providing tools and libraries to generate RSA key pairs, sign requests, and enable secure authentication for trading and account management.
Introduction
Rivest–Shamir–Adleman (RSA) is a popular encryption method that uses two keys—a public key to encrypt information and a private key to decrypt it, keeping data secure.
This article details its definition and the history behind the algorithm. It discusses the limitations of earlier cryptographic methods that RSA addresses, highlighting why it has become a foundational and widely adopted public-key cryptosystem in the security community.
The article then provides guidance on generating private and public keys, and explains the basic process of encryption, decryption, signing, and verifying. Finally, it demonstrates how to use these keys with Binance APIs.
Why Was RSA Created?
Security
Enable secure communication without shared secrets: RSA allows two parties to communicate securely without needing to share a secret key in advance, solving the key distribution problem inherent in symmetric cryptography.
Establish a strong security foundation based on hard mathematical problems: RSA’s security relies on the computational difficulty of factoring large composite numbers, providing a robust cryptographic basis.
Protect confidentiality and integrity: RSA encryption ensures that messages remain confidential and unaltered during transmission.
Non-repudiation
Support digital signatures for authentication: RSA enables users to sign messages digitally, proving the message’s origin.
Guarantee the source of the signature: Because only the signer possesses the private key, the signature uniquely identifies the signer.
Prevent denial of signature (non-repudiation): The signer cannot deny having signed the message, which is critical for legal and transactional trust.
Usability
Address limitations of symmetric cryptography: Symmetric key systems require secure key exchange and do not scale well for large networks.
Simplify key management: RSA’s public-key infrastructure allows public keys to be openly distributed, reducing the complexity of key distribution.
Enable secure communication between unknown parties: Parties can communicate securely without prior arrangements.
Practicality
Provide a practical public-key encryption method: RSA was the first widely adopted algorithm that made public-key cryptography feasible for real-world applications.
Enable a wide range of cryptographic protocols: RSA supports encryption, digital signatures, and key exchange, making it versatile.
Facilitate adoption of secure electronic commerce and communication: RSA’s practicality helped drive the growth of secure online transactions and communications.
Use Cases
RSA is a common way to keep information safe by turning it into a secret code that only the person with the right private key can unlock. It also helps prove who sent a message by using digital signatures, showing that the message is real and hasn’t been changed.
RSA is also used to check if software or files are genuine by letting creators sign them, so users know they are safe to use. It helps with secure logins too, allowing people to prove who they are without sharing passwords. Because of these uses, RSA is very important for keeping digital information secure.
Some popular use cases of RSA:
Secure Website Connections (HTTPS): RSA is used during the initial connection between the browser and a website to securely exchange encryption keys. This process ensures that all data you share with the site, like passwords or payment details, is encrypted and protected from eavesdroppers.
Email Encryption and Digital Signatures: RSA allows users to encrypt their emails so only the intended recipient can read them. It also enables digital signatures, which verify the sender’s identity and ensure the message hasn’t been altered.
Software Authenticity Verification: Developers use RSA to digitally sign software and updates. This helps users confirm that the software is genuine and hasn’t been tampered with, protecting against malware and fraud.
Examples of generating and verifying a signature
# Import required modules
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
# Generate RSA key pair
key = RSA.generate(2048)
private_key = key
public_key = key.publickey()
message = b"my authenticated message"
# Hash the message
h = SHA256.new(message)
# Sign the message hash with the private key
signature = pkcs1_15.new(private_key).sign(h)
# Verify the signature with the public key
try:
pkcs1_15.new(public_key).verify(h, signature)
print("Signature is valid")
except (ValueError, TypeError):
print("Signature is invalid")How Are RSA Keys Generated?
The preferred method to generate private and public keys is to use the Binance key generator, which makes the process easy as the generation can be fully done through a clear User Interface.
The generation can also be done using openssl via command line:
Generate the private key without passphrase:
openssl genrsa -out my-prv-key.pem 2048Generate the private key with passphrase:
openssl genrsa -aes256 -out my-prv-key.pem 2048Generate the public key from private key:
openssl rsa -in my-prv-key.pem -pubout -outform PEM -out my-pub-key.pemHow to use an RSA signature with Binance
Prepare the request parameters:
For WebSocket APIs, all parameters must be sorted in ascending order before generating the signature. This ensures consistency in signature generation.
For REST APIs, parameters do not need to be sorted before signing. The signature is generated based on the exact request parameters as they are provided.
Generate the RSA signature:
RSA with API secret key can be used to sign the relevant parameters.
RSA private key can be used by registering a public key on Binance. For detailed steps, refer to How to Generate an RSA Key Pair to Send API Requests on Binance.
Include the signature in the request:
Attach the generated signature to the API request as the signature parameter.
Example: How to sign a request using RSA private key for Binance APIs
import time
import urllib.parse
from base64 import b64encode
from Crypto.Hash import SHA256
from Crypto.PublicKey import ECC
from Crypto.Signature import pkcs1_15, eddsa
api_key = "your_api_key"
# Define request parameters
params = {
"symbol": "BTCUSDT",
"side": "BUY",
"type": "LIMIT",
"quantity": 1,
"price": 45000,
"timestamp": int(time.time() * 1000)
}
def rsa_signature(private_key, payload, private_key_pass=None):
private_key = RSA.import_key(private_key, passphrase=private_key_pass)
h = SHA256.new(payload.encode("utf-8"))
signature = pkcs1_15.new(private_key).sign(h)
return b64encode(signature)
# Create the query string
query_string = urllib.parse.urlencode(params)
with open("myprivatekey.pem", "rt") as f:
data = f.read()
signature = rsa_signature(data, query_string)
# Final request URL
url = f"https://api.binance.com/api/v3/order?{query_string}&signature={signature}"
print("Signed Request URL:", url)Example: How to use the Binance Python connector
from binance_sdk_spot.spot import Spot, ConfigurationRestAPI, SPOT_REST_API_PROD_URL
# RSA Keys
configuration_rest_api = ConfigurationRestAPI(
api_key = "",
private_key = "./private_key.pem",
private_key_pass = "<password_if_applicable>",
base_path = SPOT_REST_API_PROD_URL
)
client = Spot(config_rest_api=configuration_rest_api)
# Get account and balance information
response = client.rest_api.get_account()
print(response.data())
# Post a new order
params = {
'symbol': 'BTCUSDT',
'side': 'SELL',
'type': 'LIMIT',
'time_in_force': 'GTC',
'quantity': 0.002,
'price': 9500
}
response = client.rest_api.new_order(**params)
print(response.data())Automated Signature Generation
For developers looking to automate the signature generation process across different programming languages, Binance provides an open-source repository with examples in Python, JavaScript, Java, and more. This can be accessed in the GitHub repository binance-signature-examples.
Using this resource, developers can quickly integrate RSA-based authentication into their applications with minimal effort.
For those testing Binance API integrations in a sandbox environment, you can generate an RSA private key using the Binance Testnet. This allows developers to experiment with API authentication without affecting live trading accounts.
Closing Thoughts
RSA remains a foundational asymmetric cryptographic algorithm, widely trusted for its strong security and versatility in modern applications. While it may not match the signature speed of newer algorithms like ED25519, RSA provides robust security through well-established mathematical principles and extensive real-world use. Its ability to securely encrypt data and verify digital signatures makes it a reliable choice for protecting sensitive information.
At Binance, RSA continues to be supported across various APIs and services, ensuring compatibility and secure operations. By leveraging RSA, Binance maintains a proven and secure cryptographic framework that underpins critical functions such as secure communications, identity verification, and transaction integrity.
After understanding RSA key generation and signature processes, these can be effectively used to securely authenticate and authorize actions, including placing market orders on Binance.
Further Reading
HMAC Signature: What It Is and How to Use It for Binance API Security
ED25519 Signature: What Is It and How To Use It for Binance API Security
Disclaimer: This article is for educational purposes only. This content is presented to you on an “as is” basis for general information and educational purposes only, without representation or warranty of any kind. It should not be construed as financial, legal or other professional advice, nor is it intended to recommend the purchase of any specific product or service. You should seek your own advice from appropriate professional advisors. Products mentioned in this article may not be available in your region. Where the article is contributed by a third party contributor, please note that those views expressed belong to the third party contributor, and do not necessarily reflect those of Binance Academy. Please read our full disclaimer here for further details. Digital asset prices can be volatile. The value of your investment may go down or up and you may not get back the amount invested. You are solely responsible for your investment decisions and Binance Academy is not liable for any losses you may incur. This material should not be construed as financial, legal or other professional advice. For more information, see our Terms of Use and Risk Warning.