| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
package net.i2p.crypto.eddsa.math.bigint; |
| 13 |
|
| 14 |
import java.io.Serializable; |
| 15 |
import java.math.BigInteger; |
| 16 |
|
| 17 |
import net.i2p.crypto.eddsa.math.Encoding; |
| 18 |
import net.i2p.crypto.eddsa.math.Field; |
| 19 |
import net.i2p.crypto.eddsa.math.FieldElement; |
| 20 |
|
| 21 |
public class BigIntegerLittleEndianEncoding extends Encoding implements Serializable { |
| 22 |
private static final long serialVersionUID = 3984579843759837L; |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
private BigInteger mask; |
| 27 |
|
| 28 |
@Override |
| 29 |
public synchronized void setField(Field f) { |
| 30 |
super.setField(f); |
| 31 |
mask = BigInteger.ONE.shiftLeft(f.getb()-1).subtract(BigInteger.ONE); |
| 32 |
} |
| 33 |
|
| 34 |
public byte[] encode(FieldElement x) { |
| 35 |
return encode(((BigIntegerFieldElement)x).bi.and(mask)); |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
public byte[] encode(BigInteger x) { |
| 47 |
if (f == null) |
| 48 |
throw new IllegalStateException("field not set"); |
| 49 |
byte[] in = x.toByteArray(); |
| 50 |
byte[] out = new byte[f.getb()/8]; |
| 51 |
for (int i = 0; i < in.length; i++) { |
| 52 |
out[i] = in[in.length-1-i]; |
| 53 |
} |
| 54 |
for (int i = in.length; i < out.length; i++) { |
| 55 |
out[i] = 0; |
| 56 |
} |
| 57 |
return out; |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
public FieldElement decode(byte[] in) { |
| 70 |
if (f == null) |
| 71 |
throw new IllegalStateException("field not set"); |
| 72 |
if (in.length != f.getb()/8) |
| 73 |
throw new IllegalArgumentException("Not a valid encoding"); |
| 74 |
return new BigIntegerFieldElement(f, toBigInteger(in).and(mask)); |
| 75 |
} |
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
public BigInteger toBigInteger(byte[] in) { |
| 84 |
byte[] out = new byte[in.length]; |
| 85 |
for (int i = 0; i < in.length; i++) { |
| 86 |
out[i] = in[in.length-1-i]; |
| 87 |
} |
| 88 |
return new BigInteger(1, out); |
| 89 |
} |
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
public boolean isNegative(FieldElement x) { |
| 100 |
return ((BigIntegerFieldElement)x).bi.testBit(0); |
| 101 |
} |
| 102 |
} |