-
Notifications
You must be signed in to change notification settings - Fork 108
/
CipherCodec.scala
140 lines (119 loc) · 5.01 KB
/
CipherCodec.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*
* Copyright (c) 2013, Scodec
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 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.
*/
package scodec
package codecs
import java.security.Key
import java.security.spec.AlgorithmParameterSpec
import javax.crypto.{BadPaddingException, Cipher, IllegalBlockSizeException}
import scodec.bits.BitVector
/** Represents the ability to create a `Cipher` for encryption or decryption.
*
* Used in conjunction with [[encrypted]].
*/
trait CipherFactory:
/** Creates a cipher initialized for encryption. */
def newEncryptCipher: Cipher
/** Creates a cipher initialized for decryption. */
def newDecryptCipher: Cipher
/** Companion for [[CipherFactory]].
*/
object CipherFactory:
/** Creates a cipher factory for the specified transformation (via `Cipher.getInstance(transformation)`)
* and using the specified functions for initializing for encryption and decryption respectively.
*/
def apply(
transformation: String,
initForEncryption: Cipher => Unit,
initForDecryption: Cipher => Unit
): CipherFactory =
new SimpleCipherFactory(transformation, initForEncryption, initForDecryption)
/** Creates a cipher factory for the specified transformation (via `Cipher.getInstance(transformation)`).
*
* Ciphers are initialized with the specified key only.
*/
def apply(transformation: String, key: Key): CipherFactory =
new SimpleCipherFactory(
transformation,
_.init(Cipher.ENCRYPT_MODE, key),
_.init(Cipher.DECRYPT_MODE, key)
)
/** Creates a cipher factory for the specified transformation (via `Cipher.getInstance(transformation)`).
*
* Ciphers are initialized with the specified key and algorithm parameter specification.
*/
def apply(transformation: String, key: Key, spec: AlgorithmParameterSpec): CipherFactory =
new SimpleCipherFactory(
transformation,
_.init(Cipher.ENCRYPT_MODE, key, spec),
_.init(Cipher.DECRYPT_MODE, key, spec)
)
private class SimpleCipherFactory(
transformation: String,
initForEncryption: Cipher => Unit,
initForDecryption: Cipher => Unit
) extends CipherFactory:
private def newCipher: Cipher = Cipher.getInstance(transformation).nn
def newEncryptCipher: Cipher =
val cipher = newCipher
initForEncryption(cipher)
cipher
def newDecryptCipher: Cipher =
val cipher = newCipher
initForDecryption(cipher)
cipher
/** @see [[encrypted]] */
private[codecs] final class CipherCodec[A](codec: Codec[A], cipherFactory: CipherFactory)
extends Codec[A]:
override def sizeBound = SizeBound.unknown
override def encode(a: A) =
codec.encode(a).flatMap(b => encrypt(b))
private def encrypt(bits: BitVector) =
val blocks = bits.toByteArray
try
val encrypted = cipherFactory.newEncryptCipher.doFinal(blocks).nn
Attempt.successful(BitVector(encrypted))
catch
case _: IllegalBlockSizeException =>
Attempt.failure(Err(s"Failed to encrypt: invalid block size ${blocks.size}"))
override def decode(buffer: BitVector) =
decrypt(buffer).flatMap { result =>
codec.decode(result).map {
_.mapRemainder(_ => BitVector.empty)
}
}
private def decrypt(buffer: BitVector): Attempt[BitVector] =
val blocks = buffer.toByteArray
try
val decrypted = cipherFactory.newDecryptCipher.doFinal(blocks).nn
Attempt.successful(BitVector(decrypted))
catch
case e @ (_: IllegalBlockSizeException | _: BadPaddingException) =>
Attempt.failure(Err("Failed to decrypt: " + e.getMessage))
override def toString = s"cipher($codec)"