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 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
|
/*
* Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8297878
* @summary RSA_KEM example
* @modules java.base/sun.security.jca
* java.base/sun.security.rsa
* java.base/sun.security.util
* java.base/javax.crypto:+open
*/
import sun.security.jca.JCAUtil;
import sun.security.rsa.RSACore;
import sun.security.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
// This test implements RSA-KEM as described in RFC 5990. In this KEM, the
// sender configures the encapsulator with an RSAKEMParameterSpec object.
// This object is encoded as a byte array and included in the Encapsulated
// output. The receiver is then able to recover the same RSAKEMParameterSpec
// object from the encoding using an AlgorithmParameters implementation
// and use the object to configure the decapsulator.
public class RSA_KEM {
public static void main(String[] args) throws Exception {
Provider p = new ProviderImpl();
RSAKEMParameterSpec[] kspecs = new RSAKEMParameterSpec[] {
RSAKEMParameterSpec.kdf1("SHA-256", "AES_128/KW/NoPadding"),
RSAKEMParameterSpec.kdf1("SHA-512", "AES_256/KW/NoPadding"),
RSAKEMParameterSpec.kdf2("SHA-256", "AES_128/KW/NoPadding"),
RSAKEMParameterSpec.kdf2("SHA-512", "AES_256/KW/NoPadding"),
RSAKEMParameterSpec.kdf3("SHA-256", new byte[10], "AES_128/KW/NoPadding"),
RSAKEMParameterSpec.kdf3("SHA-256", new byte[0], "AES_128/KW/NoPadding"),
RSAKEMParameterSpec.kdf3("SHA-512", new byte[0], "AES_128/KW/NoPadding"),
};
for (RSAKEMParameterSpec kspec : kspecs) {
System.err.println("---------");
System.err.println(kspec);
AlgorithmParameters d = AlgorithmParameters.getInstance("RSA-KEM", p);
d.init(kspec);
AlgorithmParameters s = AlgorithmParameters.getInstance("RSA-KEM", p);
s.init(d.getEncoded());
AlgorithmParameterSpec spec = s.getParameterSpec(AlgorithmParameterSpec.class);
if (!spec.toString().equals(kspec.toString())) {
throw new RuntimeException(spec.toString());
}
}
byte[] msg = "hello".getBytes(StandardCharsets.UTF_8);
byte[] iv = new byte[16];
for (int size : List.of(1024, 2048)) {
KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
g.initialize(size);
KeyPair kp = g.generateKeyPair();
for (RSAKEMParameterSpec kspec : kspecs) {
SecretKey cek = KeyGenerator.getInstance("AES").generateKey();
KEM kem1 = getKemImpl(p);
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, cek, new IvParameterSpec(iv));
byte[] ciphertext = c.doFinal(msg);
KEM.Encapsulator e = kem1.newEncapsulator(kp.getPublic(), kspec, null);
KEM.Encapsulated enc = e.encapsulate(0, e.secretSize(), "AES");
Cipher c2 = Cipher.getInstance(kspec.encAlg);
c2.init(Cipher.WRAP_MODE, enc.key());
byte[] ek = c2.wrap(cek);
AlgorithmParameters a = AlgorithmParameters.getInstance("RSA-KEM", p);
a.init(enc.params());
KEM kem2 = getKemImpl(p);
KEM.Decapsulator d = kem2.newDecapsulator(kp.getPrivate(), a.getParameterSpec(AlgorithmParameterSpec.class));
SecretKey k = d.decapsulate(enc.encapsulation(), 0, d.secretSize(), "AES");
Cipher c3 = Cipher.getInstance(kspec.encAlg);
c3.init(Cipher.UNWRAP_MODE, k);
cek = (SecretKey) c3.unwrap(ek, "AES", Cipher.SECRET_KEY);
Cipher c4 = Cipher.getInstance("AES/CBC/PKCS5Padding");
c4.init(Cipher.DECRYPT_MODE, cek, new IvParameterSpec(iv));
byte[] cleartext = c4.doFinal(ciphertext);
if (!Arrays.equals(cleartext, msg)) {
throw new RuntimeException();
}
System.out.printf("%4d %20s - %11d %11d %11d %11d %s\n",
size, kspec,
e.secretSize(), e.encapsulationSize(),
d.secretSize(), d.encapsulationSize(), k.getAlgorithm());
}
}
}
// To bypass the JCE security provider signature check
private static KEM getKemImpl(Provider p) throws Exception {
var ctor = KEM.class.getDeclaredConstructor(
String.class, KEMSpi.class, Provider.class);
ctor.setAccessible(true);
return ctor.newInstance("RSA-KEM", new KEMImpl(), p);
}
static final String RSA_KEM = "1.2.840.113549.1.9.16.3.14";
static final String KEM_RSA = "1.0.18033.2.2.4";
public static class ProviderImpl extends Provider {
public ProviderImpl() {
super("MYKEM", "1", "RSA-KEM");
List<String> alias = List.of(RSA_KEM, "OID." + RSA_KEM);
Map<String, String> attrs = Map.of(
"SupportedKeyClasses", "java.security.interfaces.RSAKey");
putService(new Service(this, "KEM", "RSA-KEM",
"RSA_KEM$KEMImpl", alias, attrs));
putService(new Service(this, "AlgorithmParameters", "RSA-KEM",
"RSA_KEM$AlgorithmParametersImpl", alias, attrs));
}
}
public static class AlgorithmParametersImpl extends AlgorithmParametersSpi {
RSAKEMParameterSpec spec;
@Override
protected void engineInit(AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException {
if (paramSpec instanceof RSAKEMParameterSpec rspec) {
spec = rspec;
} else {
throw new InvalidParameterSpecException();
}
}
@Override
protected void engineInit(byte[] params) throws IOException {
spec = decode(params);
}
@Override
protected void engineInit(byte[] params, String format) throws IOException {
spec = decode(params);
}
@Override
protected <T extends AlgorithmParameterSpec> T engineGetParameterSpec(
Class<T> paramSpec) throws InvalidParameterSpecException {
if (paramSpec.isAssignableFrom(RSAKEMParameterSpec.class)) {
return paramSpec.cast(spec);
} else {
throw new InvalidParameterSpecException();
}
}
@Override
protected byte[] engineGetEncoded() {
return encode(spec);
}
@Override
protected byte[] engineGetEncoded(String format) {
return encode(spec);
}
@Override
protected String engineToString() {
return spec == null ? "<null>" : spec.toString();
}
static final ObjectIdentifier id_rsa_kem;
static final ObjectIdentifier id_kem_rsa;
static final ObjectIdentifier id_kdf1;
static final ObjectIdentifier id_kdf2;
static final ObjectIdentifier id_kdf3;
static {
try {
id_rsa_kem = ObjectIdentifier.of("1.2.840.113549.1.9.16.3.14");
id_kem_rsa = ObjectIdentifier.of("1.0.18033.2.2.4");
id_kdf1 = ObjectIdentifier.of("1.3.133.16.840.9.44.1.0"); // fake
id_kdf2 = ObjectIdentifier.of("1.3.133.16.840.9.44.1.1");
id_kdf3 = ObjectIdentifier.of("1.3.133.16.840.9.44.1.2");
} catch (IOException e) {
throw new AssertionError(e);
}
}
static byte[] encode(RSAKEMParameterSpec spec) {
DerOutputStream kdf = new DerOutputStream()
.write(DerValue.tag_Sequence, new DerOutputStream()
.putOID(oid4(spec.kdfAlg))
.write(DerValue.tag_Sequence, new DerOutputStream()
.putOID(oid4(spec.hashAlg))))
.putInteger(spec.kdfLen());
// The next line is not in RFC 5990
if (spec.fixedInfo != null) {
kdf.putOctetString(spec.fixedInfo);
}
return new DerOutputStream()
.write(DerValue.tag_Sequence, new DerOutputStream()
.write(DerValue.tag_Sequence, new DerOutputStream()
.putOID(id_kem_rsa)
.write(DerValue.tag_Sequence, kdf))
.write(DerValue.tag_Sequence, new DerOutputStream()
.putOID(oid4(spec.encAlg)))).toByteArray();
}
static RSAKEMParameterSpec decode(byte[] der) throws IOException {
String kdfAlg, encAlg, hashAlg;
int kdfLen;
byte[] fixedInfo;
DerInputStream d2 = new DerValue(der).toDerInputStream();
DerInputStream d3 = d2.getDerValue().toDerInputStream();
if (!d3.getOID().equals(id_kem_rsa)) {
throw new IOException("not id_kem_rsa");
}
DerInputStream d4 = d3.getDerValue().toDerInputStream();
DerInputStream d5 = d4.getDerValue().toDerInputStream();
kdfLen = d4.getInteger();
fixedInfo = d4.available() > 0 ? d4.getOctetString() : null;
d4.atEnd();
ObjectIdentifier kdfOid = d5.getOID();
if (kdfOid.equals(id_kdf1)) {
kdfAlg = "kdf1";
} else if (kdfOid.equals(id_kdf2)) {
kdfAlg = "kdf2";
} else if (kdfOid.equals(id_kdf3)) {
kdfAlg = "kdf3";
} else {
throw new IOException("unknown kdf");
}
DerInputStream d6 = d5.getDerValue().toDerInputStream();
String hashOID = d6.getOID().toString();
KnownOIDs k = KnownOIDs.findMatch(hashOID);
hashAlg = k == null ? hashOID : k.stdName();
d6.atEnd();
d5.atEnd();
d3.atEnd();
DerInputStream d7 = d2.getDerValue().toDerInputStream();
String encOID = d7.getOID().toString();
KnownOIDs e = KnownOIDs.findMatch(encOID);
encAlg = e == null ? encOID : e.stdName();
d7.atEnd();
d2.atEnd();
if (kdfLen != RSAKEMParameterSpec.kdfLen(encAlg)) {
throw new IOException("kdfLen does not match encAlg");
}
return new RSAKEMParameterSpec(kdfAlg, hashAlg, fixedInfo, encAlg);
}
static ObjectIdentifier oid4(String s) {
return switch (s) {
case "kdf1" -> id_kdf1;
case "kdf2" -> id_kdf2;
case "kdf3" -> id_kdf3;
default -> {
KnownOIDs k = KnownOIDs.findMatch(s);
if (k == null) throw new UnsupportedOperationException();
yield ObjectIdentifier.of(k);
}
};
}
}
public static class RSAKEMParameterSpec implements AlgorithmParameterSpec {
private final String kdfAlg;
private final String hashAlg;
private final byte[] fixedInfo;
private final String encAlg;
private RSAKEMParameterSpec(String kdfAlg, String hashAlg, byte[] fixedInfo, String encAlg) {
this.hashAlg = hashAlg;
this.kdfAlg = kdfAlg;
this.fixedInfo = fixedInfo == null ? null : fixedInfo.clone();
this.encAlg = encAlg;
}
public static RSAKEMParameterSpec kdf1(String hashAlg, String encAlg) {
return new RSAKEMParameterSpec("kdf1", hashAlg, null, encAlg);
}
public static RSAKEMParameterSpec kdf2(String hashAlg, String encAlg) {
return new RSAKEMParameterSpec("kdf2", hashAlg, null, encAlg);
}
public static RSAKEMParameterSpec kdf3(String hashAlg, byte[] fixedInfo, String encAlg) {
return new RSAKEMParameterSpec("kdf3", hashAlg, fixedInfo, encAlg);
}
public int kdfLen() {
return RSAKEMParameterSpec.kdfLen(encAlg);
}
public static int kdfLen(String encAlg) {
return Integer.parseInt(encAlg, 4, 7, 10) / 8;
}
public String hashAlgorithm() {
return hashAlg;
}
public String kdfAlgorithm() {
return kdfAlg;
}
public byte[] fixedInfo() {
return fixedInfo == null ? null : fixedInfo.clone();
}
public String getEncAlg() {
return encAlg;
}
@Override
public String toString() {
return String.format("[%s,%s,%s]", kdfAlg, hashAlg, encAlg);
}
}
public static class KEMImpl implements KEMSpi {
@Override
public KEMSpi.EncapsulatorSpi engineNewEncapsulator(
PublicKey pk, AlgorithmParameterSpec spec, SecureRandom secureRandom)
throws InvalidAlgorithmParameterException, InvalidKeyException {
if (!(pk instanceof RSAPublicKey rpk)) {
throw new InvalidKeyException("Not an RSA key");
}
return Handler.newEncapsulator(spec, rpk, secureRandom);
}
@Override
public KEMSpi.DecapsulatorSpi engineNewDecapsulator(
PrivateKey sk, AlgorithmParameterSpec spec)
throws InvalidAlgorithmParameterException, InvalidKeyException {
if (!(sk instanceof RSAPrivateCrtKey rsk)) {
throw new InvalidKeyException("Not an RSA key");
}
return Handler.newDecapsulator(spec, rsk);
}
static class Handler implements KEMSpi.EncapsulatorSpi, KEMSpi.DecapsulatorSpi {
private final RSAPublicKey rpk; // not null for encapsulator
private final RSAPrivateKey rsk; // not null for decapsulator
private final RSAKEMParameterSpec kspec; // not null
private final SecureRandom sr; // not null for encapsulator
Handler(AlgorithmParameterSpec spec, RSAPublicKey rpk, RSAPrivateCrtKey rsk, SecureRandom sr)
throws InvalidAlgorithmParameterException {
this.rpk = rpk;
this.rsk = rsk;
this.sr = sr;
if (spec != null) {
if (spec instanceof RSAKEMParameterSpec rs) {
this.kspec = rs;
} else {
throw new InvalidAlgorithmParameterException();
}
} else {
this.kspec = RSAKEMParameterSpec
.kdf2("SHA-256", "AES_256/KW/NoPadding");
}
}
static Handler newEncapsulator(AlgorithmParameterSpec spec, RSAPublicKey rpk, SecureRandom sr)
throws InvalidAlgorithmParameterException {
if (sr == null) {
sr = JCAUtil.getDefSecureRandom();
}
return new Handler(spec, rpk, null, sr);
}
static Handler newDecapsulator(AlgorithmParameterSpec spec, RSAPrivateCrtKey rsk)
throws InvalidAlgorithmParameterException {
return new Handler(spec, null, rsk, null);
}
@Override
public SecretKey engineDecapsulate(byte[] encapsulation,
int from, int to, String algorithm)
throws DecapsulateException {
Objects.checkFromToIndex(from, to, kspec.kdfLen());
Objects.requireNonNull(algorithm, "null algorithm");
Objects.requireNonNull(encapsulation, "null encapsulation");
if (encapsulation.length != KeyUtil.getKeySize(rsk) / 8) {
throw new DecapsulateException("incorrect encapsulation size");
}
try {
byte[] Z = RSACore.rsa(encapsulation, rsk, false);
return new SecretKeySpec(kdf(Z), from, to - from, algorithm);
} catch (BadPaddingException e) {
throw new DecapsulateException("cannot decrypt", e);
}
}
@Override
public KEM.Encapsulated engineEncapsulate(int from, int to, String algorithm) {
Objects.checkFromToIndex(from, to, kspec.kdfLen());
Objects.requireNonNull(algorithm, "null algorithm");
int nLen = rpk.getModulus().bitLength();
int nSize = (nLen + 7) / 8;
BigInteger z;
int tried = 0;
while (true) {
z = new BigInteger(nLen, sr);
if (z.compareTo(rpk.getModulus()) < 0) {
break;
}
if (tried++ > 20) {
throw new ProviderException("Cannot get good random number");
}
}
byte[] Z = z.toByteArray();
if (Z.length > nSize) {
Z = Arrays.copyOfRange(Z, Z.length - nSize, Z.length);
} else if (Z.length < nSize) {
byte[] tmp = new byte[nSize];
System.arraycopy(Z, 0, tmp, nSize - Z.length, Z.length);
Z = tmp;
}
byte[] c;
try {
c = RSACore.rsa(Z, rpk);
} catch (BadPaddingException e) {
throw new AssertionError(e);
}
return new KEM.Encapsulated(
new SecretKeySpec(kdf(Z), from, to - from, algorithm),
c, AlgorithmParametersImpl.encode(kspec));
}
byte[] kdf(byte[] input) {
String hashAlg = kspec.hashAlgorithm();
MessageDigest md;
try {
md = MessageDigest.getInstance(hashAlg);
} catch (NoSuchAlgorithmException e) {
throw new ProviderException(e);
}
String kdfAlg = kspec.kdfAlgorithm();
byte[] fixedInput = kspec.fixedInfo();
int length = kspec.kdfLen();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int n = kdfAlg.equals("kdf1") ? 0 : 1;
while (true) {
switch (kdfAlg) {
case "kdf1", "kdf2" -> {
md.update(input);
md.update(u32str(n));
}
case "kdf3" -> {
md.update(u32str(n));
md.update(input);
md.update(fixedInput);
}
default -> throw new ProviderException();
}
bout.writeBytes(md.digest());
if (bout.size() > length) break;
n++;
}
byte[] result = bout.toByteArray();
return result.length == length
? result
: Arrays.copyOf(result, length);
}
@Override
public int engineSecretSize() {
return kspec.kdfLen();
}
@Override
public int engineEncapsulationSize() {
return KeyUtil.getKeySize(rsk == null ? rpk : rsk) / 8;
}
}
}
static byte[] u32str(int i) {
return new byte[] {
(byte)(i >> 24), (byte)(i >> 16), (byte)(i >> 8), (byte)i };
}
}
|