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
|
package org.bouncycastle.jcajce.provider.symmetric.util;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.MacSpi;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEParameterSpec;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
public class BaseMac
extends MacSpi implements PBE
{
private Mac macEngine;
private int pbeType = PKCS12;
private int pbeHash = SHA1;
private int keySize = 160;
protected BaseMac(
Mac macEngine)
{
this.macEngine = macEngine;
}
protected BaseMac(
Mac macEngine,
int pbeType,
int pbeHash,
int keySize)
{
this.macEngine = macEngine;
this.pbeType = pbeType;
this.pbeHash = pbeHash;
this.keySize = keySize;
}
protected void engineInit(
Key key,
AlgorithmParameterSpec params)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
CipherParameters param;
if (key == null)
{
throw new InvalidKeyException("key is null");
}
if (key instanceof BCPBEKey)
{
BCPBEKey k = (BCPBEKey)key;
if (k.getParam() != null)
{
param = k.getParam();
}
else if (params instanceof PBEParameterSpec)
{
param = PBE.Util.makePBEMacParameters(k, params);
}
else
{
throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
}
}
else if (params instanceof IvParameterSpec)
{
param = new ParametersWithIV(new KeyParameter(key.getEncoded()), ((IvParameterSpec)params).getIV());
}
else if (params == null)
{
param = new KeyParameter(key.getEncoded());
}
else
{
throw new InvalidAlgorithmParameterException("unknown parameter type.");
}
macEngine.init(param);
}
protected int engineGetMacLength()
{
return macEngine.getMacSize();
}
protected void engineReset()
{
macEngine.reset();
}
protected void engineUpdate(
byte input)
{
macEngine.update(input);
}
protected void engineUpdate(
byte[] input,
int offset,
int len)
{
macEngine.update(input, offset, len);
}
protected byte[] engineDoFinal()
{
byte[] out = new byte[engineGetMacLength()];
macEngine.doFinal(out, 0);
return out;
}
}
|