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
|
package org.bouncycastle.openpgp.operator;
import java.io.IOException;
import java.math.BigInteger;
import org.bouncycastle.bcpg.ContainedPacket;
import org.bouncycastle.bcpg.MPInteger;
import org.bouncycastle.bcpg.PublicKeyEncSessionPacket;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKey;
public abstract class PublicKeyKeyEncryptionMethodGenerator
extends PGPKeyEncryptionMethodGenerator
{
private PGPPublicKey pubKey;
protected PublicKeyKeyEncryptionMethodGenerator(
PGPPublicKey pubKey)
{
this.pubKey = pubKey;
switch (pubKey.getAlgorithm())
{
case PGPPublicKey.RSA_ENCRYPT:
case PGPPublicKey.RSA_GENERAL:
break;
case PGPPublicKey.ELGAMAL_ENCRYPT:
case PGPPublicKey.ELGAMAL_GENERAL:
break;
case PGPPublicKey.ECDH:
break;
case PGPPublicKey.DSA:
throw new IllegalArgumentException("Can't use DSA for encryption.");
case PGPPublicKey.ECDSA:
throw new IllegalArgumentException("Can't use ECDSA for encryption.");
default:
throw new IllegalArgumentException("unknown asymmetric algorithm: " + pubKey.getAlgorithm());
}
}
public byte[][] processSessionInfo(
byte[] encryptedSessionInfo)
throws PGPException
{
byte[][] data;
switch (pubKey.getAlgorithm())
{
case PGPPublicKey.RSA_ENCRYPT:
case PGPPublicKey.RSA_GENERAL:
data = new byte[1][];
data[0] = convertToEncodedMPI(encryptedSessionInfo);
break;
case PGPPublicKey.ELGAMAL_ENCRYPT:
case PGPPublicKey.ELGAMAL_GENERAL:
byte[] b1 = new byte[encryptedSessionInfo.length / 2];
byte[] b2 = new byte[encryptedSessionInfo.length / 2];
System.arraycopy(encryptedSessionInfo, 0, b1, 0, b1.length);
System.arraycopy(encryptedSessionInfo, b1.length, b2, 0, b2.length);
data = new byte[2][];
data[0] = convertToEncodedMPI(b1);
data[1] = convertToEncodedMPI(b2);
break;
case PGPPublicKey.ECDH:
data = new byte[1][];
data[0] = encryptedSessionInfo;
break;
default:
throw new PGPException("unknown asymmetric algorithm: " + pubKey.getAlgorithm());
}
return data;
}
private byte[] convertToEncodedMPI(byte[] encryptedSessionInfo)
throws PGPException
{
try
{
return new MPInteger(new BigInteger(1, encryptedSessionInfo)).getEncoded();
}
catch (IOException e)
{
throw new PGPException("Invalid MPI encoding: " + e.getMessage(), e);
}
}
public ContainedPacket generate(int encAlgorithm, byte[] sessionInfo)
throws PGPException
{
return new PublicKeyEncSessionPacket(pubKey.getKeyID(), pubKey.getAlgorithm(), processSessionInfo(encryptSessionInfo(pubKey, sessionInfo)));
}
abstract protected byte[] encryptSessionInfo(PGPPublicKey pubKey, byte[] sessionInfo)
throws PGPException;
}
|