Skip to content

Commit

Permalink
Merge pull request #56 from VirgilSecurity/v5
Browse files Browse the repository at this point in the history
V5
  • Loading branch information
kmuzychko authored Aug 9, 2019
2 parents 0fff41b + 3456580 commit 334e624
Show file tree
Hide file tree
Showing 27 changed files with 166 additions and 127 deletions.
40 changes: 39 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,42 @@ matrix:
- os: osx
language: generic
env: PYTHON=3.7.1 PYTHON_VERSION=3.7
- os: windows
language: shell
before_install:
- choco install python2
- python -m pip install --upgrade pip
env:
- PATH=/c/Python27:/c/Python27/Scripts:$PATH
- HOMEPATH=\\Users\\travis
- HOMEDRIVE='C:'
- os: windows
language: shell
before_install:
- choco install python --version 3.5.4
- python -m pip install --upgrade pip
env:
- PATH=/c/Python35:/c/Python35/Scripts:$PATH
- HOMEPATH=\\Users\\travis
- HOMEDRIVE='C:'
- os: windows
language: shell
before_install:
- choco install python --version 3.6.7
- python -m pip install --upgrade pip
env:
- PATH=/c/Python36:/c/Python36/Scripts:$PATH
- HOMEPATH=\\Users\\travis
- HOMEDRIVE='C:'
- os: windows
language: shell
before_install:
- choco install python --version 3.7.2
- python -m pip install --upgrade pip
env:
- PATH=/c/Python37:/c/Python37/Scripts:$PATH
- HOMEPATH=\\Users\\travis
- HOMEDRIVE='C:'

before_install: |
if [ "$TRAVIS_OS_NAME" == "osx" ]; then
Expand All @@ -38,8 +74,9 @@ before_install: |
export PATH="/Users/travis/.pyenv/shims:${PATH}"
pyenv-virtualenv venv
source venv/bin/activate
python --version
fi
python --version
install:
- echo $VIRGIL_APP_KEY_CONTENT_V5 > ~/tests.virgilkey
Expand All @@ -48,6 +85,7 @@ install:

script:
- pwd
- python -c "import platform; print(platform.system()); import os; print(os.getenv(\"HOME\")); print(os.getenv(\"HOMEPATH\")); print(os.getenv(\"HOMEDRIVE\"))"
- python -m unittest discover -s virgil_sdk/tests -p "*_test.py"

notifications:
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,10 @@ crypto = VirgilCrypto()


# generate a key pair
key_pair = crypto.generate_keys()
key_pair = crypto.generate_key_pair()

# save Alice private key into key sotrage
private_key_storage = PrivateKeyStorage()
private_key_storage = PrivateKeyStorage(crypto)
private_key_storage.store(key_pair.private_key, "Alice")


Expand Down
70 changes: 23 additions & 47 deletions examples/encrypt_decrypt_large_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,69 +32,45 @@
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

from virgil_crypto import VirgilCrypto, VirgilSeqCipher
import io
from virgil_crypto import VirgilCrypto

CHUNK_SIZE = 1024


def read_in_chunks(file_obj, chunk_size=CHUNK_SIZE): # Helper for chunked read file
while True:
data = file_obj.read(chunk_size)
if not data:
break
yield data


if __name__ == '__main__':

# instantiate VirgilCrypto
crypto = VirgilCrypto()
large_file = open("/PATH/TO/YOU/FILE", "rb")

chunk_list = []
# Generate new new key pair
key_pair1 = crypto.generate_key_pair()

for chunk in read_in_chunks(large_file):
chunk_list.append(bytearray(chunk))
crypto = VirgilCrypto()

large_file.close()
############ Encrypt #################
large_file = open("/PATH/TO/YOU/FILE", "rb") # Use file like a byte stream
encrypt_output_stream = io.BytesIO() # Use sample byte stream

# Generate new new key pair
key_pair1 = crypto.generate_keys()
crypto.encrypt_stream(
large_file,
encrypt_output_stream,
key_pair1.public_key
)

############ Encrypt #################
encrypt_seq_cipher = VirgilSeqCipher() # Initialize Sequence Cipher
encrypt_seq_cipher.addKeyRecipient(key_pair1.public_key.identifier, key_pair1.public_key.raw_key) # Adding recipient for encryption
large_file.close()

encrypted_chunks = list() # encrypted output
encrypted_chunks.append(encrypt_seq_cipher.startEncryption()) # start encryption
encrypt_stream_data = encrypt_output_stream.getvalue() # Get all bytes from stream

for index, chunk in enumerate(chunk_list):
encrypted_chunks.append(encrypt_seq_cipher.process(chunk)) # encryption body
if index == len(chunk_list) - 1:
try:
last_piece = encrypt_seq_cipher.finish()
if last_piece:
encrypted_chunks.append(last_piece)
except Exception as e:
print(e)

############ Decrypt ##################
decrypt_seq_cipher = VirgilSeqCipher() # Initialize Sequence Cipher
decrypt_seq_cipher.startDecryptionWithKey(key_pair1.private_key.identifier, key_pair1.private_key.raw_key) # Start decryption with our recipient private key

decrypted_chunks = list()
for index, chunk in enumerate(encrypted_chunks):
decrypted_chunks.append(decrypt_seq_cipher.process(chunk)) # decryption body
if index == len(encrypted_chunks) - 1:
print("Last index", index)
try:
last_piece = decrypt_seq_cipher.finish()
if last_piece:
decrypted_chunks.append(last_piece)
except Exception as e:
print(e)
decrypt_input_stream = io.BytesIO(encrypt_stream_data) # Create sample byte stream from encrypted in previous example bytes
new_large_file = open("/PATH/TO/YOU/DECRYPTED/FILE", "wb") # Create new file for decrypted data and use it as output stream

new_large_file = open("/PATH/TO/YOU/DECRYPTED/FILE", "wb") # Create new file for decrypted data
crypto.decrypt_stream(
decrypt_input_stream,
new_large_file,
key_pair1.private_key
)

for chunk in decrypted_chunks: # write decrypted data into recently created file.
new_large_file.write(bytearray(chunk))
new_large_file.close()
4 changes: 2 additions & 2 deletions examples/publish_card_from_client_side.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def authenticated_query_to_server(token_context, token_ttl=300):
api_key_id = "" # FILL THIS FIELD

# Loading key for next usage
imported_api_private_key = crypto.import_private_key(Utils.b64decode(api_private_key))
imported_api_private_key = crypto.import_private_key(Utils.b64decode(api_private_key)).private_key

# Instantiate token generator
builder = JwtGenerator(
Expand Down Expand Up @@ -115,7 +115,7 @@ def authenticate_on_server(username):
)

# generating key pair for creating card
key_pair = crypto.generate_keys()
key_pair = crypto.generate_key_pair()

# user identity for creating card
username = "" # FILL THIS FIELD
Expand Down
4 changes: 2 additions & 2 deletions examples/sample_backend_for_jwt_generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def generate_jwt(identity):
token_ttl = 10 # token time to live in seconds

# Loading key for next usage
imported_api_private_key = crypto.import_private_key(Utils.b64decode(api_private_key))
imported_api_private_key = crypto.import_private_key(Utils.b64decode(api_private_key)).private_key

# Instantiate token generator
builder = JwtGenerator(
Expand All @@ -77,7 +77,7 @@ def generate_jwt(identity):
def authenticate():
resp = Response()

loaded_data = json.loads(request.data) # loading data from request
loaded_data = json.loads(request.data.decode()) # loading data from request
if "identity" not in loaded_data.keys():
resp.status_code = 400
return resp
Expand Down
2 changes: 1 addition & 1 deletion examples/search_card_on_client_side.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def authenticated_query_to_server(token_context, token_ttl=300):
api_key_id = "" # FILL THIS FIELD

# Loading key for next usage
imported_api_private_key = crypto.import_private_key(Utils.b64decode(api_private_key))
imported_api_private_key = crypto.import_private_key(Utils.b64decode(api_private_key)).private_key

# Instantiate token generator
builder = JwtGenerator(
Expand Down
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Topic :: Security :: Cryptography",
],
],
install_requires=["virgil_crypto>=5.0.0"],
license="BSD",
description="""
Virgil Security provides a set of APIs for adding security to any application. In a few simple steps you can encrypt communication, securely store data, provide passwordless login, and ensure data integrity.
Expand Down
2 changes: 1 addition & 1 deletion virgil_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__version__ = "5.2.1"
__version__ = "5.3.0"
__author__ = "Virgil Security"

from .cards import CardManager
Expand Down
4 changes: 2 additions & 2 deletions virgil_sdk/cards/card_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def __init__(
self.__api_url = api_url

def generate_raw_card(self, private_key, public_key, identity, previous_card_id="", extra_fields=None):
# type: (PrivateKey, PublicKey, str, Optional[str], Optional[dict]) -> RawSignedModel
# type: (VirgilPrivateKey, VirgilPublicKey, str, Optional[str], Optional[dict]) -> RawSignedModel
"""
Args:
Expand All @@ -87,7 +87,7 @@ def generate_raw_card(self, private_key, public_key, identity, previous_card_id=
The instance of newly published Card.
"""
current_time = Utils.to_timestamp(datetime.datetime.utcnow())
raw_card = RawSignedModel.generate(public_key, identity, current_time, previous_card_id)
raw_card = RawSignedModel.generate(self._card_crypto.export_public_key(public_key), identity, current_time, previous_card_id)
self.model_signer.self_sign(raw_card, private_key, extra_fields=extra_fields)
return raw_card

Expand Down
4 changes: 2 additions & 2 deletions virgil_sdk/cards/raw_card_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class RawCardContent(object):
def __init__(
self,
identity, # type: str
public_key, # type: PublicKey
public_key, # type: Union[bytearray, bytes, Tuple[int], List[int]]
created_at, # type datetime
version="5.0", # type: str
previous_card_id=None, # type: str
Expand Down Expand Up @@ -175,7 +175,7 @@ def content_snapshot(self):
if not self._content_snapshot:
content = {
"identity": self._identity,
"public_key": Utils.b64encode(self._public_key.raw_key),
"public_key": Utils.b64encode(self._public_key),
"version": self._version,
"created_at": self._created_at,
}
Expand Down
4 changes: 2 additions & 2 deletions virgil_sdk/client/raw_signed_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,12 @@ def signatures(self):

@classmethod
def generate(cls, public_key, identity, created_at, previous_card_id=None):
# type: (PublicKey, str, int, Optional[str]) -> RawSignedModel
# type: (Union[bytearray, Tuple[int], List[int]], str, int, Optional[str]) -> RawSignedModel
"""
Generate card RawSignedModel.
Args:
public_key: Card public key.
public_key: Card public key bytes.
identity: Unique card identity.
created_at: Creation timestamp.
previous_card_id: Previous card ID.
Expand Down
4 changes: 2 additions & 2 deletions virgil_sdk/signers/model_signer.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def __init__(
self.__card_crypto = card_crypto

def sign(self, model, signer, signer_private_key, signature_snapshot=None, extra_fields=None):
# type: (RawSignedModel, str, PrivateKey, Union[bytearray, bytes], dict) -> None
# type: (RawSignedModel, str, VirgilPrivateKey, Union[bytearray, bytes], dict) -> None
"""
Adds signature to the specified RawSignedModel using specified signer.
Expand Down Expand Up @@ -83,7 +83,7 @@ def sign(self, model, signer, signer_private_key, signature_snapshot=None, extra
model.add_signature(signature)

def self_sign(self, model, signer_private_key, signature_snapshot=None, extra_fields=None):
# type: (RawSignedModel, PrivateKey, Union[bytearray, bytes], dict) -> None
# type: (RawSignedModel, VirgilPrivateKey, Union[bytearray, bytes], dict) -> None
"""
Adds owner's signature to the specified RawSignedModel using specified signer.
Expand Down
4 changes: 2 additions & 2 deletions virgil_sdk/storage/key_entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,13 @@ def __init__(
meta # type: dict
):
self.__name = name
self.__value = value
self.__value = bytearray(value)
self.__meta = meta

def to_json(self):
return Utils.json_dumps({
"name": self.__name,
"value": self.__value,
"value": list(self.__value),
"meta": self.__meta
})

Expand Down
2 changes: 1 addition & 1 deletion virgil_sdk/storage/key_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def __init__(self):
def __key_storage_path(self):
home = None
if platform.system() == "Windows":
home = os.getenv("HOMEPATH")
home = os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH")
if platform.system() == "Linux" or platform.system() == "Darwin":
home = os.getenv("HOME")
if not home:
Expand Down
2 changes: 1 addition & 1 deletion virgil_sdk/storage/private_key_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def load(self, name):
if not name:
ValueError("No alias provided for key load.")
key_entry = self.key_storage.load(name)
private_key = self.__key_exporter.import_private_key(key_entry["value"])
private_key = self.__key_exporter.import_private_key(key_entry["value"]).private_key
return private_key, key_entry["meta"]

def delete(self, name):
Expand Down
7 changes: 3 additions & 4 deletions virgil_sdk/tests/base_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,8 @@ def _app_private_key(self):
raw_private_key = bytearray(Utils.b64decode(key_file.read()))

self.__app_private_key = self._crypto.import_private_key(
key_data=raw_private_key,
password=config.VIRGIL_APP_KEY_PASSWORD
)
key_data=raw_private_key
).private_key
return self.__app_private_key

@property
Expand Down Expand Up @@ -128,7 +127,7 @@ def some_hash(identity):
return identity

def publish_card(self, username, previous_card_id=None):
key_pair = self._crypto.generate_keys()
key_pair = self._crypto.generate_key_pair()
return self.__get_manager().publish_card(
identity=username,
public_key=key_pair.public_key,
Expand Down
Loading

0 comments on commit 334e624

Please sign in to comment.